我正在尝试执行以下操作但失败了:
class base {}
class derived1 : base {}
class derived2 : base {}
interface itr<t>
where t : class, base
{}
class c1: itr<derived1>
{}
class c2 : itr<derived2>
{}
//下面2次注册失败:
_unityContainer.RegisterType<itr<base>, c1>("c1");
_unityContainer.RegisterType<itr<base>, c2>("c2");
我得到的错误是上述注册中的第二个参数无法转换为第一个参数并且此注册无效。关于如何执行此操作有什么建议吗?
我需要执行上述操作而不是将 derived1 或 derived2 类注册为通用参数,因为在解析时我不想知道我正在解析的确切派生类型。我只想以多态方式使用基类型方法。
最佳答案
你不能这样做,因为泛型不是协变的。即类型 itr<derived1>
无法转换为 itr<base>
, 即使 derived1
可以转换为base
.
这是一个使用框架 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);
因此正在访问 list1[1]
会返回盒装 int
在声明包含 string
的列表中
因此,这种转换是不允许的,因为它会破坏类型系统。
(附带说明,在子句 where t : class, base
中,您无需指定 class
。base
本身是引用类型,因此 class
约束是多余的。)
关于c# - Unity registerType 泛型参数的多态解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269279/