我有一个通用的包装类,它有时可以接收一个数组类型作为它的泛型。 我可以通过IsArray属性判断提供的泛型类型是否为数组。 但有没有办法可以在代码中获取数组元素的类型? 我查看了Type对象的所有暴露属性,但没有看到它。
例:
public class wrap<T> { public void doSomething() { if (typeof(T).IsArray) Type arrayElementType = typeof(T).??? ; } } // typeof(T) when an array is "int[]" // typeof(T).BaseType is "System.Array" // how to get "int" out of this?I have a generic wrapper class which can sometimes receive an array type as its generic. I can tell if the supplied generic type is an array by the IsArray property. But is there a way that I can obtain the type of the array elements in code? I've looked at all the exposed attributes of a Type object and just not seeing it.
Example:
public class wrap<T> { public void doSomething() { if (typeof(T).IsArray) Type arrayElementType = typeof(T).??? ; } } // typeof(T) when an array is "int[]" // typeof(T).BaseType is "System.Array" // how to get "int" out of this?最满意答案
您正在寻找Type.GetElementType方法。
Type arrayElementType = typeof(T).GetElementType();在派生类中重写时,返回当前数组,指针或引用类型所包含或引用的对象的Type。
You're looking for the Type.GetElementType method.
Type arrayElementType = typeof(T).GetElementType();When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type.
更多推荐
发布评论