我正在编写一个简单的代码生成应用程序来从DB2数据库模式构建POCO.我知道这没关系,但我更喜欢使用类型别名而不是实际的系统类型名称(如果它们可用),即"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; }
Run Code Online (Sandbox Code Playgroud)
提前致谢.
Type t = typeof(bool);
string typeName = t.Name;
Run Code Online (Sandbox Code Playgroud)
在这个简单的例子中,typeName将具有该值"Boolean".我想知道是否/如何让它说出来"bool".
对于int/Int32,double/Double,string/String也是如此.
我想得到一个System.Type给定的string指定(原始)类型的C#友好名称,基本上是C#编译器在读取C#源代码时的方式.
我觉得描述我所追求的是以单元测试形式出现的最佳方式.
我希望存在一种通用技术可以使所有下面的断言通过,而不是试图对特殊C#名称的特殊情况进行硬编码.
Type GetFriendlyType(string typeName){ ...??... }
void Test(){
// using fluent assertions
GetFriendlyType( "bool" ).Should().Be( typeof(bool) );
GetFriendlyType( "int" ).Should().Be( typeof(int) );
// ok, technically not a primitive type... (rolls eyes)
GetFriendlyType( "string" ).Should().Be( typeof(string) );
// fine, I give up!
// I want all C# type-aliases to work, not just for primitives
GetFriendlyType( "void" ).Should().Be( typeof(void) );
GetFriendlyType( "decimal" ).Should().Be( typeof(decimal) );
//Bonus points: get type of fully-specified CLR types
GetFriendlyName( …Run Code Online (Sandbox Code Playgroud) 为什么typeof(string).FullName给予System.String而不给予string?同样是与所有其他"简单"类型,如int,float,double,...
我明白这typeof是返回System.Type给定类型的对象,但为什么string不是一个System.Type对象呢?
是因为它string是c#语言的System.Type一部分,并且是系统库的一部分吗?
可能重复:
如何在C#中获取类型的原始名称?
我在C#中有以下代码:
Assembly sysAssembly = 0.GetType().Assembly;
Type[] sysTypes = sysAssembly.GetTypes();
foreach (Type sysType in sysTypes)
{
if (sysType.IsPrimitive && sysType.IsPublic)
Console.WriteLine(sysType.Name);
}
Run Code Online (Sandbox Code Playgroud)
此代码输出:
Boolean,Byte,Char,Double,Int16,Int32,Int64,IntPtr,SByte,Single,UInt16,UInt32,UInt64,UIntPtr,
我想在可能的情况下替换Booleanby bool,Byteby byte等,而不依赖于固定的数组或字典.有没有办法做到这一点?