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

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


当前回答

使用3dGrabber的解决方案:

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

//and now

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

其他回答

试试这个。

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

(注意:我假设您所知道的都是对象或IList或类似的,并且列表可以是运行时的任何类型)

如果您知道它是一个列表<T>,那么:

Type type = abc.GetType().GetGenericArguments()[0];

另一种选择是查看索引器:

Type type = abc.GetType().GetProperty("Item").PropertyType;

使用新的TypeInfo:

using System.Reflection;
// ...
var type = abc.GetType().GetTypeInfo().GenericTypeArguments[0];
public bool IsCollection<T>(T value){
  var valueType = value.GetType();
  return valueType.IsArray() || typeof(IEnumerable<object>).IsAssignableFrom(valueType) || typeof(IEnumerable<T>).IsAssignableFrom(valuetype);
}

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

T checkType = default(T);

if (checkType is MyClass)
{}

GetGenericArgument()方法必须在实例的Base Type(其类是泛型类myClass<T>)上设置。否则,它将返回类型[0]。

例子:

Myclass<T> instance = new Myclass<T>();
Type[] listTypes = typeof(instance).BaseType.GetGenericArguments();