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

Tom*_*han 83 c# generics

如果我有方法签名就好

public string myMethod<T>( ... )
Run Code Online (Sandbox Code Playgroud)

我怎样才能在方法中获取作为类型参数给出的类型的名称?我想做类似的事情typeof(T).FullName,但这确实有效......

Ree*_*sey 131

你的代码应该有效. typeof(T).FullName完全有效.这是一个完全编译的功能程序:

using System;

class Program 
{
    public static string MyMethod<T>()
    {
        return typeof(T).FullName;
    }

    static void Main(string[] args)
    {
        Console.WriteLine(MyMethod<int>());

        Console.ReadKey();
    }

}
Run Code Online (Sandbox Code Playgroud)

运行以上打印(按预期):

System.Int32
Run Code Online (Sandbox Code Playgroud)

  • 这对我很有帮助,因为我假设 `nameof(T)` 和 `typeof(T).Name` 会做同样的事情。结果 `nameof(T)` 只是返回 `T`。 (2认同)

Pau*_*ith 7

此扩展方法输出非泛型类型的简单类型名称,并附加泛型类型的泛型参数列表。这适用于您无需担心内部泛型参数(如IDictionary<int, IDictionary<int, string>>.

using System;
using System.Linq;

namespace Extensions
{ 
    public static class TypeExtensions
    {
        /// <summary>
        /// Returns the type name. If this is a generic type, appends
        /// the list of generic type arguments between angle brackets.
        /// (Does not account for embedded / inner generic arguments.)
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>System.String.</returns>
        public static string GetFormattedName(this Type type)
        {
            if(type.IsGenericType)
            {
                string genericArguments = type.GetGenericArguments()
                                    .Select(x => x.Name)
                                    .Aggregate((x1, x2) => $"{x1}, {x2}");
                return $"{type.Name.Substring(0, type.Name.IndexOf("`"))}"
                     + $"<{genericArguments}>";
            }
            return type.Name;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用递归并将“.Select(x =&gt; x.Name)”替换为“.Select(x =&gt; x.GetFormattedName())”。这样所有类型都会被格式化。 (4认同)
  • 甚至更好;`string.Join(",", type.GetGenericArguments().Select(GetFormattedName))` (3认同)

Jim*_*Aho 6

你的代码应该可以工作。您还可以获取类的名称而不是包括命名空间的全名,例如:

using System;

namespace ConsoleApp1
{
    class Program
    {
        public static string GettingName<T>() => typeof(T).Name;

        public static string GettingFullName<T>() => typeof(T).FullName;

        static void Main(string[] args)
        {
            Console.WriteLine($"Name: {GettingName<decimal>()}");
            Console.WriteLine($"FullName: {GettingFullName<decimal>()}");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

运行上述程序的输出是:

Name: Decimal
FullName: System.Decimal
Run Code Online (Sandbox Code Playgroud)

这是上述代码的 dotnet fiddle,您可以尝试一下


GR7*_*GR7 5

typeof(T).Nametypeof(T).FullName正在为我工作。我得到类型作为参数传递。

  • 啊。如果您传递的类型是 Nullable,要获取基础类型,您必须使用 typeof (T).GetGenericArguments()[0] 之类的东西 (2认同)
  • 要检查类型是否可为空,您可以使用 typeof(T).IsGenericType,如果是,您可以使用以下代码来获取 Name 或 FUllName ((Type)typeof(T).GetGenericArguments()[0 ])。姓名 (2认同)