我如何获得泛型类型参数的类型名称? [英] How do I get the type name of a generic type argument?

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

问题描述

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

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

这篇关于我如何获得泛型类型参数的类型名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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