今天在写代码的时候碰到一个CS1973编译错误。
代码如下:
<%: Html.TextBox("Hello", ViewBag.Value) %>
发现问题了吗?下面是错误描述:
Compiler Error Message: CS1973: ‘System.Web.Mvc.HtmlHelper<object>’ has no applicable method named ‘TextBox’ but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
通过描述发现,问题是出在ASP.NET MVC 3新引入的ViewBag上面,由于它实际是一个dynamic类型,而dynamic类型又不能使用扩展方面(Extension Method)。因为扩展方面是编译时的,是将扩展的类型传入静态方法。但dynamic的机制是运行时的,他需要运行时解析数据类型并调用其方法或属性。如果将dynamic类型传入扩展方法,编译器将无法选择合适的重载方法,将抛出此编译错误,注意是编译错误。
所以修复这问题的方法就是加一个类型转换,告诉编译器我们要调用哪个重载。
<%: Html.TextBox("Hello", (string)ViewBag.Value) %>
参考: