構建一個更完整的答案掉柯克的是這樣的。修改:
- 支持所有C#關鍵字
- 支持自定義翻譯
- 陣列
- Nullables是
ValueType?
代替Nullable<ValueType>
這裏是全碼:
public static class TypeTranslator
{
private static Dictionary<Type, string> _defaultDictionary = new Dictionary<System.Type, string>
{
{typeof(int), "int"},
{typeof(uint), "uint"},
{typeof(long), "long"},
{typeof(ulong), "ulong"},
{typeof(short), "short"},
{typeof(ushort), "ushort"},
{typeof(byte), "byte"},
{typeof(sbyte), "sbyte"},
{typeof(bool), "bool"},
{typeof(float), "float"},
{typeof(double), "double"},
{typeof(decimal), "decimal"},
{typeof(char), "char"},
{typeof(string), "string"},
{typeof(object), "object"},
{typeof(void), "void"}
};
public static string GetFriendlyName(this Type type, Dictionary<Type, string> translations)
{
if(translations.ContainsKey(type))
return translations[type];
else if (type.IsArray)
return GetFriendlyName(type.GetElementType(), translations) + "[]";
else if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
return type.GetGenericArguments()[0].GetFriendlyName() + "?";
else if (type.IsGenericType)
return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x)).ToArray()) + ">";
else
return type.Name;
}
public static string GetFriendlyName(this Type type)
{
return type.GetFriendlyName(_defaultDictionary);
}
}
在簡而言之,不。遞歸方法是要走的路:) – 2013-05-09 16:22:11
添加了正確的HTML格式化大於和小於... – AwkwardCoder 2013-05-09 16:42:19