HtmlHelper 扩展的动态
我习惯于在键入“this”类型后由智能感知提供扩展方法。但是,当我使用 HtmlHelper 尝试此操作时,扩展方法不会显示 - 即使存在“using”语句。这是为什么呢?为了澄清这一点,我是在常规 .cs 文件而不是 .cshtml 文件中进行此测试。没有充分的理由,我只是在玩弄 MVC 命名空间和语言来“看看它是如何运作的”。我仍然不知道为什么智能感知不能拾取所有 4000 个扩展(我夸张了,但有很多)。
说到数千个扩展,为什么这些辅助例程作为扩展方法提供?如果使用了典型的静态类,则示例剃刀签名可能会是:
@EditorExtensions.EditorFor<T>(...)
似乎可行,并且“框架设计指南”指出应该很少使用扩展,最好是:
- 仅针对接口类型。
- 仅适用于无法重新部署的类型
似乎没有任何扩展方法“标准”适用。这就是为什么我期望使用常规静态类和静态方法来填充此卷。理由是什么?
更新:非扩展助手的示例代码(供进一步讨论)
public static class MyHelper
{
public static MvcHtmlString Go(HtmlHelper foo){
foo.Raw("Hello");
return new MvcHtmlString("<p>What's up Doc</p>");
}
}
I'm accustomed to extension methods being presented by intellisense, after the 'this' type is keyed-in. But when I try this with HtmlHelper, the extension methods don't show - even though the 'using' statement is present. Why is this? To clarify, I'm doing this test from within a regular .cs file, rather than a .cshtml file. No good reason, I'm simply playing with the MVC namespace and language to "see how it ticks." I still don't know why the intellisense doesn't pick up all 4000 extensions (I exagerate, but there are many).
Speaking of thousands of extensions, why are these helper routines provided as extension methods? If typical static classes had been used, probably a sample razor signature would be:
@EditorExtensions.EditorFor<T>(...)
Seems doable, and the "Framework Design Guidelines" states that extensions should seldom be used, and preferably:
- only against interface types.
- only on types that cannot be re-deployed
It doesn't seem that any of the extension method "criteria" applies. This is why I would have expected regular static classes, with static methods to fill this roll. What was the rationale?
Update: Sample code of a non-extension helper (for further discussion)
public static class MyHelper
{
public static MvcHtmlString Go(HtmlHelper foo){
foo.Raw("Hello");
return new MvcHtmlString("<p>What's up Doc</p>");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定为什么 IntelliSense 没有为您显示
HtmlHelper
扩展方法。您确定您正在使用 System.Web.Mvc.Html
吗?这些帮助器被实现为扩展方法的原因是因为它们通常需要访问与请求、模型等相关的各种状态。如果它们仍然使帮助器可进行单元测试,那么实现此目标要困难得多。作为静态方法实现。
Not sure why IntelliSense is not showing
HtmlHelper
extension methods for you. Are you sure you areusing System.Web.Mvc.Html
?The reason why these helpers were implemented as extension methods is because they often need to have access to various state associated with the request, the model, etc. It's a lot more difficult to achieve this goal while still making the helpers unit-testable if they were implemented as static methods.