我正在使用反射来打印方法签名,例如
foreach (var pi in mi.GetParameters()) {
Console.WriteLine(pi.Name + ": " + pi.ParameterType.ToString());
}
Run Code Online (Sandbox Code Playgroud)
这很好用,但它打印出基元类型为"System.String"而不是"string"和"System.Nullable`1 [System.Int32]"而不是"int?".有没有办法在代码中查找参数的名称,例如
public Example(string p1, int? p2)
Run Code Online (Sandbox Code Playgroud)
版画
p1: string
p2: int?
Run Code Online (Sandbox Code Playgroud)
代替
p1: System.String
p2: System.Nullable`1[System.Int32]
Run Code Online (Sandbox Code Playgroud) 我想得到一个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) 可能重复:
如何在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等,而不依赖于固定的数组或字典.有没有办法做到这一点?