How to get the type of T from a member of a generic class or method?

前端 未结 16 1876
梦毁少年i
梦毁少年i 2020-11-22 02:37

Let say I have a generic member in a class or method, so:

public class Foo
{
    public List Bar { get; set; }

    public void Baz()
    {         


        
相关标签:
16条回答
  • 2020-11-22 03:07

    Using 3dGrabber's solution:

    public static T GetEnumeratedType<T>(this IEnumerable<T> _)
    {
        return default(T);
    }
    
    //and now 
    
    var list = new Dictionary<string, int>();
    var stronglyTypedVar = list.GetEnumeratedType();
    
    0 讨论(0)
  • 2020-11-22 03:09

    If you dont need the whole Type variable and just want to check the type you can easily create a temp variable and use is operator.

    T checkType = default(T);
    
    if (checkType is MyClass)
    {}
    
    0 讨论(0)
  • 2020-11-22 03:20

    Try

    list.GetType().GetGenericArguments()
    
    0 讨论(0)
  • 2020-11-22 03:20

    That's work for me. Where myList is some unknown kind of list.

    IEnumerable myEnum = myList as IEnumerable;
    Type entryType = myEnum.AsQueryable().ElementType;
    
    0 讨论(0)
  • 2020-11-22 03:21

    You can get the type of "T" from any collection type that implements IEnumerable<T> with the following:

    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;
    }
    

    Note that it doesn't support collection types that implement IEnumerable<T> twice, e.g.

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

    I suppose you could return an array of types if you needed to support this...

    Also, you might also want to cache the result per collection type if you're doing this a lot (e.g. in a loop).

    0 讨论(0)
  • 2020-11-22 03:22

    This is how i did it

    internal static Type GetElementType(this Type type)
    {
            //use type.GenericTypeArguments if exist 
            if (type.GenericTypeArguments.Any())
             return type.GenericTypeArguments.First();
    
             return type.GetRuntimeProperty("Item").PropertyType);
    }
    

    Then call it like this

    var item = Activator.CreateInstance(iListType.GetElementType());
    

    OR

    var item = Activator.CreateInstance(Bar.GetType().GetElementType());
    
    0 讨论(0)
提交回复
热议问题