【问题标题】:The model item passed into the dictionary is of type ..., but this dictionary requires ...传入字典的模型项的类型是...,但是这个字典需要...
【发布时间】:2014-10-09 08:14:29
【问题描述】:

整个错误信息:

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 是一个类,Interface1 和 Interface2 是接口

关于我正在调用的控制器操作:

return View(model);

在哪里: model 是类型...

MyClass<Implementation1,Implementation2>

...和 ​​Implementation1 实现 Interface1Implementation2 实现 Interface2

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

@model MyClass<Implementation1, Implementation2>

【问题讨论】:

  • 有什么理由不能让你的模型使用MyClass&lt;Interface1, Interface2&gt;

标签: c# asp.net-mvc


【解决方案1】:

因为MyClassinvariant 你不能这样做,这意味着MyClass&lt;Implementation1, Implementation2&gt; 不是MyClass&lt;Interface1, Interface2&gt;,因此错误。

由于它不是接口或委托,因此不能将类声明为协变。虽然您可以使用out keyword 创建一个接口并使其成为协变的:

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

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

View 中的模型声明:

@model IMyClass<Interface1, Interface2>

【讨论】:

  • 谢谢!看来我有一个设计问题。 Interface1Interface2MyClass 上的属性类型,我想在我的视图中使用。而且我可以在IMyClass 中声明它们,前提是它们是只读的,所以 htey 不会是可序列化的!
  • @LeopoldoWagner,这超出了原始问题的范围。发布另一个问题,SO 社区将很乐意提供帮助。
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 2015-07-05
相关资源
最近更新 更多