I got an System.Object (AKA object) that is simple one-dimensional array (I do a lot of checks). The element type will become known at runtime. I have to do two types of copying the array:
1) deep copy array itself but shallow copy items: - this has answer here: my previous question 2) deep copy array itself as well as its items:
I did it like that:
public object FullDeepCopy_SimpleArray(object original)
{
Type elementType = original.GetType().GetElementType();
return GetType()
.GetMethod("Create_DeepCopyArray")
.MakeGenericMethod(elementType)
.Invoke(this, new object[] { original });
}
//used in generic invoke
public T[] Create_DeepCopyArray<T>(object original)
{
T[] origArray = (T[])((Array)original).Clone();
int length = origArray.Length;
T[] copy = (T[])(Array.CreateInstance(typeof(T), length));
for (int i = 0; i < length; i++)
{
copy[i] = (T)Create_infDeep_CopyOf(origArray[i]); // this makes the deep copy of any item
}
return copy;
}
It works perfectly but it raises some problems:
- it's unsecure to work with, other programmers might delete the method
Create_DeepCopyArray
as it is only used inGetMethod
code and IDE Visual Studio doesn't recognize it as used (because it's passed as string) - Look at the number of casts in
Create_DeepCopyArray
method, I kind of think there must be a better solution
Do you have any ideas to improve this?
Aucun commentaire:
Enregistrer un commentaire