c# - 使用反射从 C# 中嵌套类型的 DeclaringType 获取泛型类型

标签 c# .net reflection

假设我有以下类结构:

public class Outer<T>
{
    public class Inner<U>
    {
    }
}

还有一些代码:

var testType = typeof(Outer<string>.Inner<int>);

如何获取构造的泛型类型 typeof(Outer<string>) ,或通用值 typeof(string)来自testType变量?

最佳答案

有趣 - 外部类型的泛型参数似乎被投影到内部类型:

var testType = typeof(Outer<string>.Inner<int>);              
var outerType = testType.DeclaringType;                       
var outerTypeGenericParam = outerType.GetGenericArguments();
var testTypeGenericParam = testType.GetGenericArguments();
Console.WriteLine(outerType);                                 // Test+Outer`1[T] 
Console.WriteLine(outerTypeGenericParam[0]);                  // T
Console.WriteLine(testTypeGenericParam[0]);                   // System.String
Console.WriteLine(testTypeGenericParam[1]);                   // System.Int32

所以你的情况中的一句话是:

testType.GetGenericArguments()[0]

关于c# - 使用反射从 C# 中嵌套类型的 DeclaringType 获取泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051292/

相关文章:

c# - 没有事件窗口的屏幕截图

c# - 不同组按特定顺序的组合

c# - 从解析字符串值的单行条件语句将 null 传递到 DataTable

.net - 在图像上绘制的 LinkLabel 文本

java - 重构测试

c# - 具有通用类型 T 的 SetValue

c# - 任务未处理的异常

c# - 如何使用动态 javascript 下拉列表进行 MVC 编辑

c# - 匿名委托(delegate)作为函数参数

c# - 在 Silverlight 的扩展方法中使用反射的深度复制?