我怎样才能获得在C#中类型的原始名字? [英] How can I get the primitive name of a type in C#?
问题描述
我使用反射来打印出一个方法签名,例如
的foreach(在mi.GetParameters VAR PI()){
Console.WriteLine(pi.Name +:+ pi.ParameterType.ToString());
}
这工作pretty很好,但它打印出原语的类型为System.String而不是串和System.Nullable`1 [System.Int32],而不是INT?有没有一种方法来获取参数的名称,因为它看起来在code,例如
公共示例(串P1,诠释?P2)
打印
P1:字符串
P2:诠释?
而不是
P1:System.String
P2:System.Nullable`1 [System.Int32]
编辑:我是在下面的答案错了一半。
看一看<一个href=\"http://msdn.microsoft.com/en-us/library/system.$c$cdom.compiler.$c$cdomprovider.gettypeoutput.aspx\"><$c$c>CSharp$c$cProvider.GetTypeOutput$c$c>.示例code:
使用Microsoft.CSharp;
使用系统;
使用系统codeDOM。类测试
{
静态无效的主要()
{
VAR编译器=新CSHARP codeProvider();
//只是为了证明这一点......
VAR型=新的codeTypeReference(typeof运算(的Int32));
Console.WriteLine(compiler.GetTypeOutput(类型)); //打印INT
}
}
不过,这种的不的翻译可空&LT; T&GT;
到 T
- 我无法找到这将使它这样做的任何选项,虽然这并不意味着这样的选择不存在:)
有什么的框架,以支持这一点 - 毕竟,他们是C#特异性名
(注意:字符串
的不是的一个的原始类型,顺便说一句。)
您必须通过发现做 Nullable`1
自己,并从完整的框架名称每个别名的地图。
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());
}
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)
prints
p1: string
p2: int?
instead of
p1: System.String
p2: System.Nullable`1[System.Int32]
EDIT: I was half wrong in the answer below.
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
}
}
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 :)
There's nothing in the framework to support this - after all, they're C#-specific names.
(Note that string
isn't a primitive type, by the way.)
You'll have to do it by spotting Nullable`1
yourself, and have a map from the full framework name to each alias.
这篇关于我怎样才能获得在C#中类型的原始名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!