相关疑难解决方法(0)

如何在C#中获取类型的原始名称?

我正在使用反射来打印方法签名,例如

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)

c# reflection

22
推荐指数
1
解决办法
7065
查看次数

将"C#friendly type"转换为实际类型:"int"=> typeof(int)

我想得到一个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)

.net c# reflection types

12
推荐指数
3
解决办法
1万
查看次数

C#,反射和原始类型

可能重复:
如何在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等,而不依赖于固定的数组或字典.有没有办法做到这一点?

c# reflection primitive-types

4
推荐指数
1
解决办法
2291
查看次数

C#类型名称而不是CLR类型名称

typeof(int).Name
Run Code Online (Sandbox Code Playgroud)

返回System.Int32会不会有人知道返回"int"的方法

c# system.type

3
推荐指数
2
解决办法
3111
查看次数

标签 统计

c# ×4

reflection ×3

.net ×1

primitive-types ×1

system.type ×1

types ×1