【发布时间】:2015-10-13 22:03:17
【问题描述】:
在通过反射探索泛型类型(例如IEnumerable<T>)时,我可以通过以下方式找到T:
public Type Demo<TSequence>()
{
return typeof(TSequence).GenericTypeArguments[0];
}
例如:
typeof(Collection<short>).GenericTypeArguments[0].FullName == "System.Int16"
数组的细节意味着这种方法不适用于数组,因为它们本身没有通用参数。我发现实际获取数组元素类型的唯一方法是:
public Type Demo<TArray>()
{
return typeof(TArray)
.GetTypeInfo()
.DeclaredMethods
.Single(m => m.Name == "Get")
.ReturnType;
}
这是一种人为、丑陋且容易出错的 hack。
如何找到数组元素的类型?
【问题讨论】:
-
typeof(TArray).GetElementType()
标签: c# reflection types