【问题标题】:Obtaining the Type of the elements in an array of generic type获取泛型数组中元素的类型
【发布时间】:2011-10-25 03:42:29
【问题描述】:

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

【问题讨论】:

    标签: c# arrays generics types


    【解决方案1】:

    您正在寻找Type.GetElementType 方法。

    在派生类中重写时,返回对象的类型 当前数组、指针或引用包含或引用 输入。

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

    【讨论】:

    • 是的,所以,我知道这会是显而易见的事情。我的临时变量也几乎是名字。非常感谢您的回答!
    • @Devoramadoomalama:干杯 - 我记得我也找了很多人。
    猜你喜欢
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多