ASP.NET MVC中htmlAttributes的匿名类和IDictionary <string,object>之间的区别?

Aza*_*ndi 5 c# asp.net-mvc idictionary asp.net-mvc-3

例如,如果检查这两个扩展方法,唯一的区别是htmlAttributes的类型,因此您可以通过两种不同的方式传递htmlAttributes:

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    IDictionary<string, object> htmlAttributes);

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    object htmlAttributes);
Run Code Online (Sandbox Code Playgroud)

并以下列方式之一使用它们:

@Html.TextBoxFor(model => model.TagLine,
    new { @placeholder = "We live to make art." })

@Html.TextBoxFor(model => model.TagLine,
    new Dictionary<string, object> { 
        { "placeholder", "We live to make art." } })
Run Code Online (Sandbox Code Playgroud)

我检查过MVC源代码,我知道在后台他们使用相同的方法,但是接受匿名对象的方法HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)用于使匿名对象成为字典.

在我看来,使用匿名对象的视图更清晰.你们觉得怎么样?使用匿名对象有什么缺点吗?

Chr*_*tow 10

没有太大的区别,但是使用匿名对象对于调用者来说是一种更清晰,更易读的语法,现在被认为是更标准的做法.如果您是微优化的粉丝,那么使用IDictionary可能会有轻微的,可忽略的性能优势.

自从ASP.NET MVC 1.0 CTP时代以来,IDictionary重载选项可能已经停滞不前,而C#3.0和匿名对象仍然很新.Eilon Lipton的博客文章提议使用C#3.0匿名类型作为词典提供了一些背景知识.

  • 在已有字典的某些情况下,字典重载很有用. (3认同)