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

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(),因为列表可能包含零元素。我该怎么做?


当前回答

试试这个。

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

其他回答

使用以下扩展方法,您可以在没有反射的情况下离开:

public static Type GetListType<T>(this List<T> _)
{
    return typeof(T);
}

或更一般:

public static Type GetEnumeratedType<T>(this IEnumerable<T> _)
{
    return typeof(T);
}

用法:

List<string>        list    = new List<string> { "a", "b", "c" };
IEnumerable<string> strings = list;
IEnumerable<object> objects = list;

Type listType    = list.GetListType();           // string
Type stringsType = strings.GetEnumeratedType();  // string
Type objectsType = objects.GetEnumeratedType();  // BEWARE: object

您可以将此选项用于泛型列表的返回类型:

public string ListType<T>(T value)
{
    var valueType = value.GetType().GenericTypeArguments[0].FullName;
    return valueType;
}

使用3dGrabber的解决方案:

public static T GetEnumeratedType<T>(this IEnumerable<T> _)
{
    return default(T);
}

//and now

var list = new Dictionary<string, int>();
var stronglyTypedVar = list.GetEnumeratedType();

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

T checkType = default(T);

if (checkType is MyClass)
{}

考虑一下:

我使用它以相同的方式导出20个类型列表:

private void Generate<T>()
{
    T item = (T)Activator.CreateInstance(typeof(T));

    ((T)item as DemomigrItemList).Initialize();

    Type type = ((T)item as DemomigrItemList).AsEnumerable().FirstOrDefault().GetType();
    if (type == null) 
        return;
    if (type != typeof(account)) // Account is listitem in List<account>
    {
        ((T)item as DemomigrItemList).CreateCSV(type);
    }
}