我如何获得泛型类型参数的类型名称?

我如何获得泛型类型参数的类型名称?

问题描述:

如果我有一个方法签名,比如

If I have a method signature like

public string myMethod<T>( ... )

如何在方法内部获取作为类型参数给出的类型的名称?我想做一些类似于 typeof(T).FullName 的东西,但实际上它可以工作...

How can I, inside the method, get the name of the type that was given as type argument? I'd like to do something similar to typeof(T).FullName, but that actually works...

你的代码应该可以工作。 typeof(T).FullName 完全有效。这是一个完全编译,功能正常的程序:

Your code should work. typeof(T).FullName is perfectly valid. This is a fully compiling, functioning program:

using System;

class Program 
{
    public static string MyMethod<T>()
    {
        return typeof(T).FullName;
    }
    static void Main(string[] args)
    {

        Console.WriteLine(MyMethod<int>());

        Console.ReadKey();
    }

}

运行上述打印):

Running the above prints (as expected):

System.Int32