3

のような方法を実装することは可能ですか?

string GetFriendlyName(Type type) { ... }

可能な場合、型のCLR エイリアスを返す .NET では? この場合GetFriendlyName(typeof(Foo))は "Foo"を返しますが、 MemberInfo.NameGetFriendlyName(typeof(int))のように "Int32" ではなく "int" を返します。

4

2 に答える 2

6

まあ、プログラムでそれを行う方法がないとは思いません。dictionarylike の代わりにa を使用できます。

public static readonly Dictionary<Type, string> aliases = new Dictionary<Type, string>()
{
    { typeof(string), "string" },
    { typeof(int), "int" },
    { typeof(byte), "byte" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(ushort), "ushort" },
    { typeof(long), "long" },
    { typeof(uint), "uint" },
    { typeof(ulong), "ulong" },
    { typeof(float), "float" },
    { typeof(double), "double" },
    { typeof(decimal), "decimal" },
    { typeof(object), "object" },
    { typeof(bool), "bool" },
    { typeof(char), "char" }
};

編集:答えを提供するための2つの質問が見つかりました

于 2013-03-18T07:09:19.663 に答える
3

この方法を試すことができます:

private string GetFriendlyName(Type type)
{
    Dictionary<string, string> alias = new Dictionary<string, string>()
        {
            {typeof (byte).Name, "byte"},
            {typeof (sbyte).Name, "sbyte"},
            {typeof (short).Name, "short"},
            {typeof (ushort).Name, "ushort"},
            {typeof (int).Name, "int"},
            {typeof (uint).Name, "uint"},
            {typeof (long).Name, "long"},
            {typeof (ulong).Name, "ulong"},
            {typeof (float).Name, "float"},
            {typeof (double).Name, "double"},
            {typeof (decimal).Name, "decimal"},
            {typeof (object).Name, "object"},
            {typeof (bool).Name, "bool"},
            {typeof (char).Name, "char"},
            {typeof (string).Name, "string"}
        };
    return alias.ContainsKey(type.Name) ? alias[type.Name] : type.Name;
}

パフォーマンス向上のためにalias辞書 を作成することをお勧めします。static readonly

于 2013-03-18T07:13:43.667 に答える