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

假设我有以下类结构:


public class Outer<T>

{

    public class Inner<U>

    {

    }

}

还有一些代码:


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

如何从变量中获取构造的泛型类型typeof(Outer<string>)或泛型的值?typeof(string)testType


PIPIONE
浏览 139回答 1
1回答

胡子哥哥

有趣 - 似乎外部类型的泛型参数被投射到内部类型:var testType = typeof(Outer<string>.Inner<int>);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;var outerType = testType.DeclaringType;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var outerTypeGenericParam = outerType.GetGenericArguments();var testTypeGenericParam = testType.GetGenericArguments();Console.WriteLine(outerType);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Test+Outer`1[T]&nbsp;Console.WriteLine(outerTypeGenericParam[0]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TConsole.WriteLine(testTypeGenericParam[0]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// System.StringConsole.WriteLine(testTypeGenericParam[1]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// System.Int32所以在你的情况下,单线将是:testType.GetGenericArguments()[0]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go