2014-10-09 208 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

相關問題