with net method español create c# .net reflection

net - reflection c# español



¿Hay alguna manera de obtener el alias de un tipo a través de la reflexión? (7)

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

Estoy escribiendo una aplicación de generación de código simple para construir 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?

//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 por adelantado.


En caso de que alguien necesite el diccionario con elementos nulables:

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


Esto no utiliza la reflexión, estrictamente hablando, pero puede obtener el alias del tipo utilizando 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

(Dicho esto, creo que las otras respuestas que sugieren que simplemente usas un mapeo de tipos CLR a alias C # son probablemente la mejor manera de hacerlo con este).


Mantenlo simple:

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


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.


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


public string GetAlias(Type t) { string typeName = ""; using (var provider = new CSharpCodeProvider()) { var typeRef = new CodeTypeReference(t); typeName = provider.GetTypeOutput(typeRef); } return typeName; }