Man*_*ish 3 c# generics inversion-of-control unity-container
我正在尝试执行以下操作并失败:
class base {}
class derived1 : base {}
class derived2 : base {}
interface itr<t>
where t : class, base
{}
class c1: itr<derived1>
{}
class c2 : itr<derived2>
{}
Run Code Online (Sandbox Code Playgroud)
//以下2个注册失败:
_unityContainer.RegisterType<itr<base>, c1>("c1");
_unityContainer.RegisterType<itr<base>, c2>("c2");
Run Code Online (Sandbox Code Playgroud)
我得到的错误是上述注册中的第二个参数不能被类型转换为第一个参数,并且该注册无效.有关如何做到这一点的任何建议?
我需要执行上述操作,而不是使用derived1或derived2类作为通用参数进行注册,因为在解析时我不想知道我正在解析的确切派生类型.我只想多态地使用基类型方法.
你不能这样做,因为泛型不是协变的.也就是说,即使itr<derived1>可以转换为类型也无法转换为.itr<base>derived1base
以下是使用框架List<T>类的原因示例:
List<string> list1 = new List<string>();
list1.Add("Hello, World!");
// This cast will fail, because the following line would then be legal:
List<object> list2 = (List<object>)list1;
// ints are objects, but they are not strings!
list2.Add(1);
Run Code Online (Sandbox Code Playgroud)
因此,访问list1[1]将返回int声明包含strings 的列表中的框.
因此,不允许此强制转换,因为它会破坏类型系统.
(作为旁注,在子句中where t : class, base,您不需要指定class. base本身是引用类型,因此class约束是多余的.)