如何在 C# 中获取类型的原始名称? [英] How can I get the primitive name of a type in C#?

查看:20
本文介绍了如何在 C# 中获取类型的原始名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using reflection to print out a method signature, e.g.

foreach (var pi in mi.GetParameters()) {
    Console.WriteLine(pi.Name + ": " + pi.ParameterType.ToString());
}

这很有效,但它打印出原语类型为System.String"而不是string"和System.Nullable`1[System.Int32]"而不是int?".有没有办法在代码中获取参数的名称,例如

This works pretty well, but it prints out the type of primitives as "System.String" instead of "string" and "System.Nullable`1[System.Int32]" instead of "int?". Is there a way to get the name of the parameter as it looks in code, e.g.

public Example(string p1, int? p2)

印刷品

p1: string
p2: int?

代替

p1: System.String
p2: System.Nullable`1[System.Int32]

推荐答案

我在下面的答案中错了一半.

I was half wrong in the answer below.

看看CSharpCodeProvider.GetTypeOutput.示例代码:

Have a look at CSharpCodeProvider.GetTypeOutput. Sample code:

using Microsoft.CSharp;
using System;
using System.CodeDom;

class Test
{
    static void Main()
    {
        var compiler = new CSharpCodeProvider();
        // Just to prove a point...
        var type = new CodeTypeReference(typeof(Int32));
        Console.WriteLine(compiler.GetTypeOutput(type)); // Prints int
    }
}

然而,这不会Nullable 翻译成 T? - 而且我找不到任何可以使它这样做,虽然这并不意味着这样的选项不存在:)

However, this doesn't translate Nullable<T> into T? - and I can't find any options which would make it do so, although that doesn't mean such an option doesn't exist :)

框架中没有任何内容支持这一点 - 毕竟,它们是 C# 特定的名称.

There's nothing in the framework to support this - after all, they're C#-specific names.

(请注意,string 不是原始类型,顺便说一句.)

(Note that string isn't a primitive type, by the way.)

您必须通过自己发现 Nullable`1 (Nullable.GetUnderlyingType 可用于此,例如),并具有从完整框架名称到每个别名的映射.

You'll have to do it by spotting Nullable`1 yourself (Nullable.GetUnderlyingType may be used for this, for example), and have a map from the full framework name to each alias.

这篇关于如何在 C# 中获取类型的原始名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆