Есть ли способ получить псевдоним типа через отражение?
Я пишу простое приложение для генерации кода для создания POCO из схемы базы данных DB2. Я знаю, это не имеет значения, но я предпочитаю использовать псевдонимы типов, а не фактическое имя типа системы, если они доступны, то есть "int", а не "Int32". Есть ли способ использовать отражение, что я могу получить псевдоним типа, а не фактический тип?
//Get the type name
var typeName = column.DataType.Name;
//If column.DataType is, say, Int64, I would like the resulting property generated
//in the POCO to be...
public long LongColumn { get; set; }
//rather than what I get now using the System.Reflection.MemberInfo.Name property:
public Int64 LongColumn { get; set; }
Спасибо заранее.
Ответы
Ответ 1
Нет - просто создайте Dictionary<Type,string>
, чтобы сопоставить все типы с их псевдонимами. Это фиксированный набор, поэтому выполнить его не сложно:
private static readonly Dictionary<Type, string> Aliases =
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" }
};
Ответ 2
Это не использует отражение, строго говоря, но вы можете получить псевдоним типа с помощью CodeDOM:
Type t = column.DataType; // Int64
string typeName;
using (var provider = new CSharpCodeProvider())
{
var typeRef = new CodeTypeReference(t);
typeName = provider.GetTypeOutput(typeRef);
}
Console.WriteLine(typeName); // long
(Сказав это, я думаю, что другие ответы, предполагающие, что вы просто используете сопоставление типов CLR с алиасами С#, вероятно, лучший способ пойти с этим.)
Ответ 3
Если кому-то нужен словарь с нулевыми значениями:
private static readonly Dictionary<Type, string> Aliases = 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(Nullable<byte>), "byte?" },
{ typeof(Nullable<sbyte>), "sbyte?" },
{ typeof(Nullable<short>), "short?" },
{ typeof(Nullable<ushort>), "ushort?" },
{ typeof(Nullable<int>), "int?" },
{ typeof(Nullable<uint>), "uint?" },
{ typeof(Nullable<long>), "long?" },
{ typeof(Nullable<ulong>), "ulong?" },
{ typeof(Nullable<float>), "float?" },
{ typeof(Nullable<double>), "double?" },
{ typeof(Nullable<decimal>), "decimal?" },
{ typeof(Nullable<bool>), "bool?" },
{ typeof(Nullable<char>), "char?" }
};
Ответ 4
Держите его простым:
var aliasDict = new Dictionary<Type, string>() {
{ typeof(int), "int" },
{ typeof(long), "long" },
// etc
}
Type reflectedType;
string aliasedTypeName = aliasDict[reflectedType];
Ответ 5
Я не думаю, что есть. Псевдоним представляет собой концепцию времени компиляции, специфичную для используемого языка Paticular.NET. После того, как вы отражаете и просматриваете тип, вы увидите истинный тип объекта .NET.
Ответ 6
Основываясь на приведенных выше двух ответах на использование Словаря, я написал 2 основных метода расширения, которые могут помочь немного сократить использование. Включая этот класс в свой проект, вы сможете использовать его просто, вызывая методы Alias () или AliasOrName() для типа, как показано ниже.
Использование примера
// 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();
Реализация;
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?" }
};
}
Ответ 7
public string GetAlias(Type t)
{
string typeName = "";
using (var provider = new CSharpCodeProvider())
{
var typeRef = new CodeTypeReference(t);
typeName = provider.GetTypeOutput(typeRef);
}
return typeName;
}