繁体   English   中英

如何在 C# 中获取类型的原始名称?

[英]How can I get the primitive name of a type in C#?

我正在使用反射打印出方法签名,例如

foreach (var pi in mi.GetParameters()) {
    Console.WriteLine(pi.Name + ": " + pi.ParameterType.ToString());
}

这工作得很好,但它打印出原语类型为“System.String”而不是“string”和“System.Nullable`1[System.Int32]”而不是“int?”。 有没有办法在代码中获取参数的名称,例如

public Example(string p1, int? p2)

印刷

p1: string
p2: int?

代替

p1: System.String
p2: System.Nullable`1[System.Int32]

编辑:我在下面的答案中错了一半。

看看CSharpCodeProvider.GetTypeOutput 示例代码:

using Microsoft.CSharp;
using System;
using System.CodeDom;

class Test
{
    static void Main()
    {
        var compiler = new CSharpCodeProvider();
        // Just to prove a point...
        var type = new CodeTypeReference(typeof(Int32));
        Console.WriteLine(compiler.GetTypeOutput(type)); // Prints int
    }
}

但是,这不会Nullable<T>转换为T? - 我找不到任何可以让它这样做的选项,尽管这并不意味着这样的选项不存在:)


框架中没有任何东西支持这一点——毕竟,它们是 C# 特定的名称。

(顺便说一下,请注意string不是原始类型。)

您必须通过自己发现Nullable`1 (例如Nullable.GetUnderlyingType可以用于此)来完成它,并拥有从完整框架名称到每个别名的映射。

这个问题有两个有趣的答案。 接受一个从乔恩斯基特 相当多说什么,他已经说了。

编辑乔恩更新了他的答案,所以它现在和我的几乎一样。 (但当然要早 20 秒)

但 Luke H 也给出了这个答案,我认为这是对 CodeDOM 的非常棒的使用。

Type t = column.DataType;    // Int64

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
    var expr = new CodeTypeReferenceExpression(t);

    var prov = new CSharpCodeProvider();
    prov.GenerateCodeFromExpression(expr, sw, new CodeGeneratorOptions());
}

Console.WriteLine(sb.ToString());    // long

不是世界上最漂亮的代码,但这就是我最终做的:(基于 Cornard 的代码)

public static string CSharpName(this Type type)
{
    if (!type.FullName.StartsWith("System"))
        return type.Name;
    var compiler = new CSharpCodeProvider();
    var t = new CodeTypeReference(type);
    var output = compiler.GetTypeOutput(t);
    output = output.Replace("System.","");
    if (output.Contains("Nullable<"))
        output = output.Replace("Nullable","").Replace(">","").Replace("<","") + "?";
    return output;
}

另一种选择,基于此处的其他答案。

特征:

  • String转换为string ,将Int32转换为int
  • Nullable<Int32>作为int? 等等
  • System.DateTime抑制为DateTime
  • 所有其他类型都是完整的

它处理我需要的简单情况,不确定它是否能很好地处理复杂类型。

Type type = /* Get a type reference somehow */
var compiler = new CSharpCodeProvider();
if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
    return compiler.GetTypeOutput(new CodeTypeReference(type.GetGenericArguments()[0])).Replace("System.","") + "?";
}
else
{
    return compiler.GetTypeOutput(new CodeTypeReference(type)).Replace("System.","");
}   

string是只是一种表象System.String - string并没有真正的幕后意味着什么。

顺便说一句,要通过System.Nullable'1[System.Int32] ,您可以使用Nullable.GetUnderlyingType(type);

这是我在大约 5 分钟的黑客攻击后想到的。 例如:

CSharpAmbiance.GetTypeName(typeof(IDictionary<string,int?>))

将返回System.Collections.Generic.IDictionary<string, int?>

public static class CSharpAmbiance
{
    private static Dictionary<Type, string> aliases =
        new Dictionary<Type, string>();

    static CSharpAmbiance()
    {
        aliases[typeof(byte)] = "byte";
        aliases[typeof(sbyte)] = "sbyte";
        aliases[typeof(short)] = "short";
        aliases[typeof(ushort)] = "ushort";
        aliases[typeof(int)] = "int";
        aliases[typeof(uint)] = "uint";
        aliases[typeof(long)] = "long";
        aliases[typeof(ulong)] = "ulong";
        aliases[typeof(char)] = "char";

        aliases[typeof(float)] = "float";
        aliases[typeof(double)] = "double";

        aliases[typeof(decimal)] = "decimal";

        aliases[typeof(bool)] = "bool";

        aliases[typeof(object)] = "object";
        aliases[typeof(string)] = "string";
    }

    private static string RemoveGenericNamePart(string name)
    {
        int backtick = name.IndexOf('`');

        if (backtick != -1)
            name = name.Substring(0, backtick);

        return name;
    }

    public static string GetTypeName(Type type)
    {
        if (type == null)
            throw new ArgumentNullException("type");

        string keyword;
        if (aliases.TryGetValue(type, out keyword))
            return keyword;

        if (type.IsArray) {
            var sb = new StringBuilder();

            var ranks = new Queue<int>();
            do {
                ranks.Enqueue(type.GetArrayRank() - 1);
                type = type.GetElementType();
            } while (type.IsArray);

            sb.Append(GetTypeName(type));

            while (ranks.Count != 0) {
                sb.Append('[');

                int rank = ranks.Dequeue();
                for (int i = 0; i < rank; i++)
                    sb.Append(',');

                sb.Append(']');
            }

            return sb.ToString();
        }

        if (type.IsGenericTypeDefinition) {
            var sb = new StringBuilder();

            sb.Append(RemoveGenericNamePart(type.FullName));
            sb.Append('<');

            var args = type.GetGenericArguments().Length - 1;
            for (int i = 0; i < args; i++)
                sb.Append(',');

            sb.Append('>');

            return sb.ToString();
        }

        if (type.IsGenericType) {
            if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
                return GetTypeName(type.GetGenericArguments()[0]) + "?";

            var sb = new StringBuilder();

            sb.Append(RemoveGenericNamePart(type.FullName));
            sb.Append('<');

            var args = type.GetGenericArguments();
            for (int i = 0; i < args.Length; i++) {
                if (i != 0)
                    sb.Append(", ");

                sb.Append(GetTypeName(args[i]));
            }

            sb.Append('>');

            return sb.ToString();
        }

        return type.FullName;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM