假设我有一个System.String[]
类型的对象。我可以查询类型对象来确定它是否是数组
Type t1 = typeof(System.String[]);
bool isAnArray = t1.IsArray; // should be true
但是,如何从t1获取数组项的类型对象
Type t2 = ....; // should be typeof(System.String)
发布于 2014-02-25 02:21:15
感谢@psaxton数组指出了comment和其他集合之间的区别。作为扩展方法:
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;
}
}
用法:
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
发布于 2017-05-07 08:02:15
感谢@drzaus的漂亮answer,但它可以被压缩成一个线条(加上对null
和IEnumerable
类型的检查):
public static Type GetEnumeratedType(this Type type) =>
type?.GetElementType()
?? typeof(IEnumerable).IsAssignableFrom(type)
? type.GenericTypeArguments.FirstOrDefault()
: null;
添加了null
检查器以避免异常,也许我不应该这样做(请随意删除Null Conditional Operators)。还添加了一个筛选器,以便该函数仅适用于集合,而不适用于任何泛型类型。
请记住,这也可能被实现的子类所欺骗,这些子类更改了集合的主题,而实现者决定将集合的泛型参数移到后面的位置。
C#8和可空性的转换答案:
public static Type GetEnumeratedType(this Type type) =>
((type?.GetElementType() ?? (typeof(IEnumerable).IsAssignableFrom(type)
? type.GenericTypeArguments.FirstOrDefault()
: null))!;
https://stackoverflow.com/questions/4129831
复制相似问题