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

前端 未结 16 2257
梦毁少年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:24

    With the following extension method you can get away without reflection:

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

    Or more general:

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

    Usage:

    List        list    = new List { "a", "b", "c" };
    IEnumerable strings = list;
    IEnumerable objects = list;
    
    Type listType    = list.GetListType();           // string
    Type stringsType = strings.GetEnumeratedType();  // string
    Type objectsType = objects.GetEnumeratedType();  // BEWARE: object
    
        

    提交回复
    热议问题