gpt4 book ai didi

c#获取泛型类中泛型类型参数的名称

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:45 30 4
gpt4 key购买 nike

我正在尝试从类类型中获取基因类的类型参数名称 ( ClassName<TypeParameterName>)。

例如这样的事情:

class MyClass<Type1>
{
public Type data;
}
static void Main()
{
Console.WriteLine(typeof(MyClass<int>).GetTypeParameterName());
//prints: Type1
}

我搜索了很多,但没有找到任何有关如何执行此操作的信息。我唯一想到的就是使用 StreamReader并阅读整个 .cs 文件并在文本中找到类型。但是有没有更快/更干净的方法来做到这一点?

注意:我不是在尝试获取 Type1 的类型,而是在尝试获取字符串“Type1”。

最佳答案

在您的示例中,您已经将泛型类型参数设置为 int,因此您不会获得 Type1

试试这个:

class MyClass<Type1>
{
public Type data;
}
static void Main()
{
Console.WriteLine(typeof(MyClass<>).GetGenericArguments()[0].Name);
//prints: Type1
}

关于c#获取泛型类中泛型类型参数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50527286/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com