2014-10-09 213 views
4

整个错误消息:传递到字典的模型产品类型...,但这需要字典...

The model item passed into the dictionary is of type 
'MyClass`2[Implementation1,Implementation2]', 
but this dictionary requires a model item of type 
'MyClass`2[Interface1,Interface2]'. 

在我看来,我有模型声明:

@model MyClass<Interface1, Interface2> 

凡MyClass的是类和接口1和接口2都在我的控制器操作界面

我打电话:

return View(model); 

其中: 模式的类型是...

​​

...和Implementation1实现接口1Implementation2工具接口2

有什么办法避免这个错误,而不必像下面那样声明我的模型?

@model MyClass<Implementation1, Implementation2> 
+0

任何原因,你不能让你的模型使用'MyClass的<接口1,接口2> '? – DavidG 2014-10-09 08:33:55

回答

3

因为MyClass不变你不能做到这一点,这意味着MyClass<Implementation1, Implementation2>MyClass<Interface1, Interface2>,因此错误。

因为它不是接口或委托,所以不能将该类声明为covariant。虽然你可以创建一个接口,使之协变使用out keyword

public interface IMyClass<out T1, out T2> 
{ 
    ... 
} 

public class MyClass<T1, T2> : IMyClass<T1, T2> 
{ 
    ... 
} 

在视图模型声明:

@model IMyClass<Interface1, Interface2> 
+0

谢谢! 看来我有一个设计问题。 'Interface1'和'Interface2'是'MyClass'上的属性类型,我想在我的视图中使用。而且我只能在'IMyClass'中声明它们,只是它们是只读的,所以htey不会被序列化! – 2014-10-09 12:56:33

+0

@LeopoldoWagner,这超出了原始问题的范围。发布另一个问题,社区将很乐意提供帮助。 – Zabavsky 2014-10-09 13:04:19

+0

@Zabavsky很高兴知道,很好的答案+1。 – 2014-10-09 20:55:43

相关问题