具有通用参数的 class 的名称?

name of class with generic parameters?

我正在尝试使用 T4 为一系列通用 classes 生成代码。

我想知道如何使用反射获得完整的 class 名称?

public class Foo<TFirst, TSecond> {}

var type = typeof(Foo<,>);
var name = type.FullName; // returns "Foo`2"

我想要的是全名以及我编写的实际通用参数名称

"Foo<TFirst, TSecond>"

请注意,它们不是已知类型,正如我所说的,我正在使用 T4 生成代码,因此我希望具有准确的命名以将其用于代码生成,例如,在泛型方法中。

我试过 this answers 但他们要求传递已知类型,这不是我想要的。

您可以使用 Type.GetGenericArguments:

通过反射访问类型参数名称
using System;

public class Foo<TFirst, TSecond> {}

class Test
{
    static void Main()
    {
        var type = typeof(Foo<,>);
        Console.WriteLine($"Full name: {type.FullName}");
        Console.WriteLine("Type argument names:");
        foreach (var arg in type.GetGenericArguments())
        {
            Console.WriteLine($"  {arg.Name}");
        }
    }
}

请注意,这是给类型 参数 命名,因为您使用了通用类型定义;如果你使用 var type = typeof(Foo<string, int>); 你会得到 StringInt32 列出(以及更长的 type.FullName。)

我自己没有写过任何 T4,所以我不知道这对你是否有用 - 为了达到 Foo<TFirst, TSecond> 你需要写一些字符串操作逻辑.但是,这是我所知道的获得 arguments/parameters.

类型的唯一方法