How to deep copy array items with unknown type at runtime without using MakeGenericMethod?

喜欢而已 提交于 2019-12-25 00:40:20

问题


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 in GetMethod 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?

来源:https://stackoverflow.com/questions/58491958/how-to-deep-copy-array-items-with-unknown-type-at-runtime-without-using-makegene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!