2009-09-01 10 views
14

Escribo una aplicación de generación de código simple para compilar POCO desde un esquema de base de datos DB2. Sé que no importa, pero prefiero usar alias de tipo en lugar del nombre del tipo de sistema real si están disponibles, es decir, "int" en lugar de "Int32". ¿Hay alguna manera de usar la reflexión de que pueda obtener el alias de un tipo en lugar de que sea el tipo real?¿Hay alguna forma de obtener el alias de un tipo mediante la reflexión?

//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; } 

Gracias de antemano.

Respuesta

37

No, solo crea un Dictionary<Type,string> para asignar todos los tipos a sus alias. Es un conjunto fijo, por lo que no es difícil de hacer:

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" } 
}; 
+0

ratas, eso es lo que pensaba. Oh, bueno, no es tanto tipear :-) –

+6

Pasta deliciosa. – oscilatingcretin

1

No creo que exista. El alias es completamente un concepto de tiempo de compilación específico para el lenguaje .NET particular que utiliza. Una vez que refleje y vea el tipo, verá el verdadero tipo .NET del objeto.

2

Que sea sencillo:

var aliasDict = new Dictionary<Type, string>() { 
    { typeof(int), "int" }, 
    { typeof(long), "long" }, 
    // etc 
} 

Type reflectedType; 
string aliasedTypeName = aliasDict[reflectedType]; 
24

Esto no utiliza la reflexión, en sentido estricto, pero se puede llegar al alias del tipo mediante el uso de 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 

(Una vez dicho esto, yo piense que las otras respuestas que sugieren que simplemente usa un mapeo de tipos CLR a alias C# son probablemente la mejor manera de hacerlo con este).

+3

+1 Interesante. – sisve

4

En caso de que alguien necesite el diccionario con nullables:

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?" } 
    }; 
1

Basado en las 2 respuestas anteriores para usar un diccionario, he escrito 2 métodos básicos de extensión que podrían ayudar a limpiar el uso un poco. Incluyendo esta clase en su proyecto, podrá usarla simplemente llamando a los métodos Alias ​​() o AliasOrName() en el tipo que se muestra a continuación.

Ejemplo de uso;

 // 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(); 

La implementación;

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?" } 
    }; 
} 
1
public string GetAlias(Type t) 
{ 
    string typeName = ""; 
    using (var provider = new CSharpCodeProvider()) 
    { 
     var typeRef = new CodeTypeReference(t); 
     typeName = provider.GetTypeOutput(typeRef); 
    } 
    return typeName; 
} 
Cuestiones relacionadas