假设我在类或方法中有一个泛型成员,如下所示:

public class Foo<T>
{
    public List<T> Bar { get; set; }
    
    public void Baz()
    {
        // get type of T
    }   
}

当我实例化该类时,T变为MyTypeObject1,因此该类具有一个通用列表属性:list<MyTypeObject1>。这同样适用于非泛型类中的泛型方法:

public class Foo
{
    public void Bar<T>()
    {
        var baz = new List<T>();
        
        // get type of T
    }
}

我想知道我的类列表包含什么类型的对象。那么,名为Bar或局部变量baz的列表属性包含什么类型的T?

我无法执行Bar[0].GetType(),因为列表可能包含零元素。我该怎么做?


当前回答

类型:

type = list.AsEnumerable().SingleOrDefault().GetType();

其他回答

以下内容对我有用。其中myList是某种未知的列表。

IEnumerable myEnum = myList as IEnumerable;
Type entryType = myEnum.AsQueryable().ElementType;

您可以从实现IEnumerable<T>的任何集合类型中获取“T”类型,方法如下:

public static Type GetCollectionItemType(Type collectionType)
{
    var types = collectionType.GetInterfaces()
        .Where(x => x.IsGenericType 
            && x.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        .ToArray();
    // Only support collections that implement IEnumerable<T> once.
    return types.Length == 1 ? types[0].GetGenericArguments()[0] : null;
}

注意,它不支持两次实现IEnumerable<t>的集合类型,例如。

public class WierdCustomType : IEnumerable<int>, IEnumerable<string> { ... }

我想,如果需要支持,可以返回一个类型数组。。。

此外,如果您经常这样做(例如在循环中),您可能还希望按收集类型缓存结果。

如果您不需要整个Type变量,只想检查类型,则可以轻松创建一个临时变量并使用is运算符。

T checkType = default(T);

if (checkType is MyClass)
{}

试试这个。

如果(类型(T)==类型(人))

如果我理解正确,您的列表具有与容器类本身相同的类型参数。如果是这种情况,那么:

Type typeParameterType = typeof(T);

如果您幸运地将对象作为类型参数,请参阅Marc的答案。