Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 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 Answer

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()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...