Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

reflection - How can I get the primitive name of a type in 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());
}

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (Nullable.GetUnderlyingType may be used for this, for example), and have a map from the full framework name to each alias.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...