I want to clone a generic object and preserve its type.
run.Append(style.Clone(BlackFont)); //run object accepts only RunProperties objects
public T Clone(T what) {
if (what is RunProperties)
return (T) what.Clone();
}
It doesn't work since T type does not have a Clone method, how can I overcome this without casting in the first statement.
run.Append((RunProperties) style.Clone(BlackFont)); //I do not want this
//not that this will work since you can't convert T to RunProperties
Thanks for any help.
---EDIT---
It seems that it would be better for my not to use generics in this case. I'll split up the data.
Here is a function I wrote that clones a record of type T, using reflection. This is a very simple implementation, I did not handle complex types etc.
public static T Clone<T>(T original)
{
T newObject = (T)Activator.CreateInstance(original.GetType());
foreach (var originalProp in original.GetType().GetProperties())
{
originalProp.SetValue(newObject, originalProp.GetValue(original));
}
return newObject;
}
I hope this can help someone.
You could always constrain the method to only accept types that implement the ICloneable interface:
public T Clone(T what) where T : ICloneable
{
if (what is RunProperties)
return (T) what.Clone();
}
But since your method really only works with one type, you could change it slightly and use the as operator also:
public T Clone(T what)
{
var castWhat = what as RunProperties;
if(castWhat != null)
return castWhat.Clone();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With