Get user-friendly name for generic type in C#

前端 未结 5 1599
自闭症患者
自闭症患者 2020-12-06 00:32

Is there an easy way without writing a recursive method which will give a \'user friendly\' name for a generic type from the Type class?

E.g. For the fo

5条回答
  •  无人及你
    2020-12-06 01:08

    You can avoid writing a recursive method by calling the recursive method that's already provided for you:

    static string GetTypeName(Type type)
    {
        var codeDomProvider = CodeDomProvider.CreateProvider("C#");
        var typeReferenceExpression = new CodeTypeReferenceExpression(new CodeTypeReference(type));
        using (var writer = new StringWriter())
        {
            codeDomProvider.GenerateCodeFromExpression(typeReferenceExpression, writer, new CodeGeneratorOptions());
            return writer.GetStringBuilder().ToString();
        }
    }
    

    Note that this includes the type namespaces, but excludes the assembly references. For the type in your question, the result looks like this:

    System.Collections.Generic.List>
    

    It isn't clear to me whether that qualifies as "something like" List>.

提交回复
热议问题