2012-10-04 103 views
2

是否可以將ExpandoObject轉換爲匿名類型的對象?將ExpandoObject轉換爲匿名類型

目前我有HtmlHelper擴展名,可以將HTML屬性作爲參數。問題是我的擴展也需要添加一些HTML屬性,所以我使用ExpandoObject來合併我的屬性和屬性,用戶使用htmlAttributes參數傳遞給函數。現在我需要將合併的HTML屬性傳遞給原始的HtmlHelper函數,並且當我發送ExpandoObject時,沒有任何反應。所以我想我需要將ExpandoObject轉換爲匿名類型的對象或類似的東西 - 任何建議都歡迎。

+1

您可以顯示助手的代碼?它會更好地說明你的目標。我懷疑你不需要任何ExpandoObject,並且可能有其他方法來實現你的目標。 –

+0

@DarinDimitrov:是的,你是對的:)我用Dictionary :)解決了這個問題 – xx77aBs

+0

[Cast ExpandoObject to anonymous type]可能重複(http://stackoverflow.com/questions/10241776/cast- expandoobject-to-anonymous-type) – nawfal

回答

3

我不認爲你需要處理expandos將實現你的目標:

public static class HtmlExtensions 
{ 
    public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes) 
    { 
     var builder = new TagBuilder("div"); 

     // define the custom attributes. Of course this dictionary 
     // could be dynamically built at runtime instead of statically 
     // initialized as in my example: 
     builder.MergeAttribute("data-myattribute1", "value1"); 
     builder.MergeAttribute("data-myattribute2", "value2"); 

     // now merge them with the user attributes 
     // (pass "true" if you want to overwrite existing attributes): 
     builder.MergeAttributes(new RouteValueDictionary(htmlAttributes), false); 

     builder.SetInnerText("hello world"); 

     return new HtmlString(builder.ToString()); 
    } 
} 

,如果你想打電話現有的一些助手,那麼一個簡單的foreach循環可以做的工作:

public static class HtmlExtensions 
{ 
    public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes) 
    { 
     // define the custom attributes. Of course this dictionary 
     // could be dynamically built at runtime instead of statically 
     // initialized as in my example: 
     var myAttributes = new Dictionary<string, object> 
     { 
      { "data-myattribute1", "value1" }, 
      { "data-myattribute2", "value2" } 
     }; 

     var attributes = new RouteValueDictionary(htmlAttributes); 
     // now merge them with the user attributes 
     foreach (var item in attributes) 
     { 
      // remove this test if you want to overwrite existing keys 
      if (!myAttributes.ContainsKey(item.Key)) 
      { 
       myAttributes[item.Key] = item.Value; 
      } 
     } 
     return htmlHelper.ActionLink("click me", "someaction", null, myAttributes); 
    } 
} 
+0

謝謝!我忘了你可以提供htmlAttributes作爲字典 :) – xx77aBs

+1

是的,順便說一下,我會建議你總是提供與RouteValueDictionary或IDictionary 一起工作的定製助手的重載。除了獲取匿名對象之外,還可以使用路由值和html屬性。 –

3

是否有可能將ExpandoObject轉換爲匿名類型的對象?

僅當您在執行時自己生成匿名類型。

匿名類型通常由編譯器在編譯時創建,並像任何其他類型一樣烘焙到您的程序集中。它們在任何意義上都不具有動態性。所以,你必須使用CodeDOM或類似的東西來生成用於匿名類型的相同類型的代碼......這不會很有趣。

我認爲更有可能是別人會創建一些知道ExpandoObject(或只能與IDictionary<string, object>一起工作)的MVC幫助類。

相關問題