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

前端 未结 16 1928
梦毁少年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: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>).GetFriendlyTypeName()
            .ShouldEqual("Dictionary>");
    }
    

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

提交回复
热议问题