【发布时间】:2022-01-21 10:49:10
【问题描述】:
using System;
interface Interface { }
class Outer<T> : Interface
where T : Interface { }
class Inner : Interface { }
public class Program
{
public static void Main()
{
Type outer = typeof(Outer<>);
Type inner = typeof(Inner);
Type expectedType = typeof(Outer<Interface>);
Type final = outer.MakeGenericType(inner);
// This works
Inner innerInstance = (Inner)Activator.CreateInstance(inner);
// This works
Outer<Inner> outerInstance = (Outer<Inner>)Activator.CreateInstance(final);
// We can cast the real type
Interface interfaceInstance = innerInstance;
// But we cant cast with the interface as the inner type
Outer<Interface> casted = (Outer<Interface>)outerInstance;
}
}
此转换将失败 (Outer<Interface>)outerInstance;,因为它无法将内部类型识别为接口。
有什么方法可以强制或将其转换为Outer<Interface> 而不是Outer<Inner>?
【问题讨论】:
-
没有。您要求的是通用方差,它不适用于类。