gpt4 book ai didi

c# - 在 C# 中访问泛型类型的 GenericTypeParameters

转载 作者:行者123 更新时间:2023-11-30 14:48:32 27 4
gpt4 key购买 nike

我想用声明的参数名称生成泛型类的名称。例如,如果我有通用类和实例化类,如下所示,我想打印 "MyClass<P1,M>" .

class MyClass<P1, M1> {}
// ... some code removed here
var myInstance = new MyClass<int,string>();

现在我得到了 myInstance 的类型信息然后像这样的泛型类型定义:

// MyClass<int,string> type info here
var type = myInstance.GetType();
// MyClass<P1, M1> type info here
var genericType = type.GetGenericTypeDefinition();

调试器显示 genericType具有所有参数名称和类型信息的属性 GenericTypeParameters。但是我无法从我的 C# 代码和转换中访问该集合 genericType System.RuntimeType 类不起作用,因为 RuntimeType 是内部的。

那么有没有办法以某种方式访问​​ GenericTypeParameters 属性,或者我在这里 SOL?环境 VS2015,.NET 4.6.1

最佳答案

我认为您只是在寻找 Type.GetGenericArguments , 你应该调用 genericType而不是 type - 在这一点上,“arguments”类型实际上是 parameters 类型,因为它是一个开放类型。

示例(为简单起见,使用 Dictionary<,>):

using System;
using System.Collections.Generic;

class Test
{
static void Main()
{
var dictionary = new Dictionary<string, int>();
var type = dictionary.GetType();
var genericType = type.GetGenericTypeDefinition();
foreach (var typeArgument in genericType.GetGenericArguments())
{
// TKey, then TValue
Console.WriteLine(typeArgument);
}
}
}

希望有了这些信息,您可以自己制定字符串格式等。

关于c# - 在 C# 中访问泛型类型的 GenericTypeParameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41308146/

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