且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用反射确定通用数组元素的类型?

更新时间:2022-11-01 14:37:38

当你有一个数组元素时,你就有了一个对象,它可以是与其他数组元素不同的类型(如派生类型).然后,您可以像处理任何独立对象一样获取单个元素数组的类型.

When you have an array element, you have an object, that can be a different type from other array elements (like a derived type). Then you can get the type of a single element array as you do for any standalone object.

你应该更换

Type typeOfthis = typeof(array[0]).GetElementType();

Type typeOfthis = array[0].GetType();

然而,当您想要创建任何类型的对象时,您可以简单地使用 Activator.CreateInstance 或从类型中检索一个 ConstructorInfo.替换

Whereas, when you want create an object of any type, you can simply using Activator.CreateInstance or retrieve one ConstructorInfo from the Type. Replace

array[i] = new typeOfthis ();

array[i] = Activator.CreateInstance(typeOfthis);

只为你知道..
- 请记住,Activator.CreateInstance 将尝试调用您传递给它的类型的无参数构造函数,那么该类型需要具有这样的构造函数.
- 您创建的对象需要与数组的 Element 类型兼容(可分配给它,就像派生类一样).
- 如果你事先知道数组的所有元素都是(或应该是)相同的类型,那么你不需要获取每个元素的类型;相反, typeof(T).GetElementType() 应该就足够了.
- 如果元素类型是一个类并且你不需要分配具体的值,因为它们是稍后分配的,或者你知道元素类型是struct,那么你不需要填充数组.

Just for you yo know..
- Remember that Activator.CreateInstance will try to call a parameterless constructor of the type you pass to it, then that type need to have such a constructor.
- The object you create need to be compatible with the array's Element type (assignable to it, like a derived class).
- If you know in advance that all elements of the array are (or should be) of the same type, then you don't need to get the type for each element; instead, typeof(T).GetElementType() should be enough.
- If the element type is a class and you don't need to assign concrete values because they are assigned later, or you know that the elementi type is struct, then you don't need to fill the array.

细节的一部分,如果你想创建一个新数组,给定它的长度和它的元素的(具体)类型,你可以尝试以下方法之一:

A part of that details, if you want to create a new array, given its length and the (concrete) type of its elements, you can try one of the following:

public static Array CreateAndFillArray(Type type, int length)
{
    var result = Array.CreateInstance(type, length);
    for (int ixItem = 0; ixItem < result.Length; ixItem++)
        result.SetValue(Activator.CreateInstance(type), ixItem);
    return result;
}
public static T[] CreateAndFillArray<T>(int length)
{
    var type = typeof(T);
    var result = new T[length];
    for (int ixItem = 0; ixItem < result.Length; ixItem++)
        result[ixItem] = (T)Activator.CreateInstance(type);
    return result;
}
public static T[] CreateAndFillArray<T>(int length)
    where T : new()
{
    var result = new T[length];
    for (int ixItem = 0; ixItem < result.Length; ixItem++)
        result[ixItem] = new T();
    return result;
}

问候,
丹尼尔.

Regards,
Daniele.