简体   繁体   English

通过反射从C#中的嵌套类型的DeclaringType获取泛型类型

[英]Getting generic type from the DeclaringType of a nested type in C# with reflection

Say I have the following class structure: 说我有以下类结构:

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

And some code: 和一些代码:

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

How can I get the constructed generic type typeof(Outer<string>) , or the value of the generic typeof(string) from the testType variable? 如何从testType变量中获取构造的泛型typeof(Outer<string>)或泛型typeof(string)的值?

Interesting - it seems that the outer type's generic argument is projected to the inner type: 有趣的是-似乎外部类型的泛型参数被投影到内部类型:

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

so the one-liner in your case would be: 因此,您的情况是:

testType.GetGenericArguments()[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM