Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

.net - Get GenericType-Name in good format using Reflection on C#

I need to get the name of generic-type in form of its declaration in code.

For example: For List<Int32> I want to get string "List<Int32>". Standart property Type.Name returns "List`1" in this situation.

EDIT: example was fixed

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using built-in functions and Linq this can be written

static string PrettyTypeName(Type t)
{
    if (t.IsArray)
    {
        return PrettyTypeName(t.GetElementType()) + "[]";
    }

    if (t.IsGenericType)
    {
        return string.Format(
            "{0}<{1}>",
            t.Name.Substring(0, t.Name.LastIndexOf("`", StringComparison.InvariantCulture)),
            string.Join(", ", t.GetGenericArguments().Select(PrettyTypeName)));
    }

    return t.Name;
}

NOTE: In pre-4.0 versions of C#, string.Join requires explicit .ToArray():

string.Join(", ", t.GetGenericArguments().Select(PrettyTypeName).ToArray()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...