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

前端 未结 16 1924
梦毁少年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 02:58

    You can use this one for return type of generic list:

    public string ListType<T>(T value)
    {
        var valueType = value.GetType().GenericTypeArguments[0].FullName;
        return valueType;
    }
    
    0 讨论(0)
  • 2020-11-22 02:58

    The GetGenericArgument() method has to be set on the Base Type of your instance (whose class is a generic class myClass<T>). Otherwise, it returns a type[0]

    Example:

    Myclass<T> instance = new Myclass<T>();
    Type[] listTypes = typeof(instance).BaseType.GetGenericArguments();
    
    0 讨论(0)
  • 2020-11-22 03:01
    public bool IsCollection<T>(T value){
      var valueType = value.GetType();
      return valueType.IsArray() || typeof(IEnumerable<object>).IsAssignableFrom(valueType) || typeof(IEnumerable<T>).IsAssignableFrom(valuetype);
    }
    
    0 讨论(0)
  • 2020-11-22 03:02

    Type:

    type = list.AsEnumerable().SingleOrDefault().GetType();
    
    0 讨论(0)
  • 2020-11-22 03:03

    If you want to know a property's underlying type, try this:

    propInfo.PropertyType.UnderlyingSystemType.GenericTypeArguments[0]
    
    0 讨论(0)
  • 2020-11-22 03:04

    I use this extension method to accomplish something similar:

    public static string GetFriendlyTypeName(this Type t)
    {
        var typeName = t.Name.StripStartingWith("`");
        var genericArgs = t.GetGenericArguments();
        if (genericArgs.Length > 0)
        {
            typeName += "<";
            foreach (var genericArg in genericArgs)
            {
                typeName += genericArg.GetFriendlyTypeName() + ", ";
            }
            typeName = typeName.TrimEnd(',', ' ') + ">";
        }
        return typeName;
    }
    
    public static string StripStartingWith(this string s, string stripAfter)
    {
        if (s == null)
        {
            return null;
        }
        var indexOf = s.IndexOf(stripAfter, StringComparison.Ordinal);
        if (indexOf > -1)
        {
            return s.Substring(0, indexOf);
        }
        return s;
    }
    

    You use it like this:

    [TestMethod]
    public void GetFriendlyTypeName_ShouldHandleReallyComplexTypes()
    {
        typeof(Dictionary<string, Dictionary<string, object>>).GetFriendlyTypeName()
            .ShouldEqual("Dictionary<String, Dictionary<String, Object>>");
    }
    

    This isn't quite what you're looking for, but it's helpful in demonstrating the techniques involved.

    0 讨论(0)
提交回复
热议问题