获取泛型类型数组中元素的类型(Obtaining the Type of the elements in an array of generic type)

编程入门 行业动态 更新时间:2024-10-24 12:28:39
获取泛型类型数组中元素的类型(Obtaining the Type of the elements in an array of generic type)

我有一个通用的包装类,它有时可以接收一个数组类型作为它的泛型。 我可以通过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。

Type arrayElementType = typeof(T).GetElementType();

You're looking for the Type.GetElementType method.

When overridden in a derived class, returns the Type of the object encompassed or referred to by the current array, pointer or reference type.

Type arrayElementType = typeof(T).GetElementType();

更多推荐

本文发布于:2023-08-01 03:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1353882.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   组中   元素   Obtaining   Type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!