无法从用法中推断出类型参数。 尝试显式指定类型参数
有人可以请我澄清一些事情。 在我的ASP.NET MVC 2应用程序中,我有一个BaseViewModel
类,其中包含以下方法:
public virtual IDictionary GetHtmlAttributes (Expression<Func> propertyExpression) { return new Dictionary(); }
我们的想法是每个子视图模型都可以覆盖此方法,并根据某些逻辑提供一组合适的html属性,以便在视图中呈现:
model.MyProperty, Model.GetHtmlAttributes (model => model.MyProperty)) %>
但是当在上面的行中使用时,当我点击视图时出现编译错误:
方法’
...BaseViewModel.GetHtmlAttributes Expression<System.Func)
的类型参数不能从用法中推断出来。 尝试显式指定类型参数。
我必须做以下事情:
model.MyProperty, Model.GetHtmlAttributes (model => model.MyProperty)) %>
我只是在寻找一些关于它如何尝试推断类型的清晰度,在HtmlHelper/TextBoxFor
扩展方法中这样做是没有问题的?
是因为视图中的HtmlHelper
会自动与页面顶部的ViewUserControl
中指定的类型相同,而我的代码可以是从BaseViewModel
inheritance的任何类型吗? 有可能以这样的方式编写它,它可以推断我的模型/属性类型?
在您的示例中,编译器无法知道TModel
应该是什么类型。 你可以做一些接近你可能尝试用扩展方法做的事情。
static class ModelExtensions { public static IDictionary GetHtmlAttributes (this TModel model, Expression> propertyExpression) { return new Dictionary(); } }
但我认为你无法拥有类似virtual
东西。
编辑:
实际上,你可以使用自引用generics做virtual
:
class ModelBase { public virtual IDictionary GetHtmlAttributes (Expression> propertyExpression) { return new Dictionary(); } } class FooModel : ModelBase { public override IDictionary GetHtmlAttributes (Expression> propertyExpression) { return new Dictionary { { "foo", "bar" } }; } }
我知道这个问题已经有了一个公认的答案,但对我来说,一个.NET初学者,有一个简单的解决方案,我做错了,我想我会分享。
我一直这样做:
@Html.HiddenFor(Model.Foo.Bar.ID)
对我有用的是改变这个:
@Html.HiddenFor(m => m.Foo.Bar.ID)
(其中“m”是表示模型对象的任意字符串)
我有同样的问题,我的解决方案:
在web.config文件中:
此错误还与缓存问题有关。
我遇到了同样的问题,只是清理并再次构建解决方案。
C#编译器只有lambda
arg => arg.MyProperty
用于推断arg类型(TModel)的一种arg.MyProperty(TProperty)。 不可能。
如果它有帮助,我在将null
传递给通用TValue
的参数时遇到了这个问题,为了解决这个问题,你必须抛出你的空值:
(string)null (int)null
等等
您指的是类型而不是实例。 在第二个和第四个代码示例中的示例中使’Model’小写。
Model.GetHtmlAttributes
应该
model.GetHtmlAttributes