Dựa trên 2 câu trả lời ở trên để sử dụng Từ điển, tôi đã viết 2 phương pháp mở rộng cơ bản có thể giúp làm sạch việc sử dụng một chút. Bao gồm cả lớp này trong dự án của bạn, bạn sẽ có thể sử dụng nó đơn giản bằng cách gọi phương thức Alias () hoặc AliasOrName() trên kiểu như được hiển thị bên dưới.
Ví dụ về cách sử dụng;
// returns int
string intAlias = typeof(Int32).Alias();
// returns int
string intAliasOrName = typeof(Int32).AliasOrName();
// returns string.empty
string dateTimeAlias = typeof(DateTime).Alias();
// returns DateTime
string dateTimeAliasOrName = typeof(DateTime).AliasOrName();
Việc triển khai;
public static class TypeExtensions
{
public static string Alias(this Type type)
{
return TypeAliases.ContainsKey(type) ?
TypeAliases[type] : string.Empty;
}
public static string AliasOrName(this Type type)
{
return TypeAliases.ContainsKey(type) ?
TypeAliases[type] : type.Name;
}
private static readonly Dictionary<Type, string> TypeAliases = new Dictionary<Type, string>
{
{ typeof(byte), "byte" },
{ typeof(sbyte), "sbyte" },
{ typeof(short), "short" },
{ typeof(ushort), "ushort" },
{ typeof(int), "int" },
{ typeof(uint), "uint" },
{ typeof(long), "long" },
{ typeof(ulong), "ulong" },
{ typeof(float), "float" },
{ typeof(double), "double" },
{ typeof(decimal), "decimal" },
{ typeof(object), "object" },
{ typeof(bool), "bool" },
{ typeof(char), "char" },
{ typeof(string), "string" },
{ typeof(void), "void" },
{ typeof(byte?), "byte?" },
{ typeof(sbyte?), "sbyte?" },
{ typeof(short?), "short?" },
{ typeof(ushort?), "ushort?" },
{ typeof(int?), "int?" },
{ typeof(uint?), "uint?" },
{ typeof(long?), "long?" },
{ typeof(ulong?), "ulong?" },
{ typeof(float?), "float?" },
{ typeof(double?), "double?" },
{ typeof(decimal?), "decimal?" },
{ typeof(bool?), "bool?" },
{ typeof(char?), "char?" }
};
}
Rats, đó là những gì tôi nghĩ. Ồ, nó không phải là nhiều đánh máy :-) –
Delicious sao chép mì ống. – oscilatingcretin