Pre*_*gha 64 .net reflection types
说我有一个System.String[]
类型对象.我可以查询类型对象以确定它是否是一个数组
Type t1 = typeof(System.String[]);
bool isAnArray = t1.IsArray; // should be true
Run Code Online (Sandbox Code Playgroud)
但是,如何从t1获取数组项的类型对象
Type t2 = ....; // should be typeof(System.String)
Run Code Online (Sandbox Code Playgroud)
Ani*_*Ani 109
您可以使用实例方法Type.GetElementType
来实现此目的.
Type t2 = t1.GetElementType();
Run Code Online (Sandbox Code Playgroud)
[返回]当前数组,指针或引用类型包含或引用的对象的类型,如果当前Type不是数组或指针,或者不通过引用传递,或者表示泛型类型,则返回null泛型类型或泛型方法定义中的类型参数.
drz*_*aus 13
感谢@psaxton 评论指出Array和其他集合之间的区别.作为扩展方法:
public static class TypeHelperExtensions
{
/// <summary>
/// If the given <paramref name="type"/> is an array or some other collection
/// comprised of 0 or more instances of a "subtype", get that type
/// </summary>
/// <param name="type">the source type</param>
/// <returns></returns>
public static Type GetEnumeratedType(this Type type)
{
// provided by Array
var elType = type.GetElementType();
if (null != elType) return elType;
// otherwise provided by collection
var elTypes = type.GetGenericArguments();
if (elTypes.Length > 0) return elTypes[0];
// otherwise is not an 'enumerated' type
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
typeof(Foo).GetEnumeratedType(); // null
typeof(Foo[]).GetEnumeratedType(); // Foo
typeof(List<Foo>).GetEnumeratedType(); // Foo
typeof(ICollection<Foo>).GetEnumeratedType(); // Foo
typeof(IEnumerable<Foo>).GetEnumeratedType(); // Foo
// some other oddities
typeof(HashSet<Foo>).GetEnumeratedType(); // Foo
typeof(Queue<Foo>).GetEnumeratedType(); // Foo
typeof(Stack<Foo>).GetEnumeratedType(); // Foo
typeof(Dictionary<int, Foo>).GetEnumeratedType(); // int
typeof(Dictionary<Foo, int>).GetEnumeratedType(); // Foo, seems to work against key
Run Code Online (Sandbox Code Playgroud)