2011-02-08 96 views
175

我想在運行時動態地將屬性添加到ExpandoObject。所以例如添加一個字符串屬性調用NewProp我想寫一些類似於動態添加屬性到ExpandoObject

var x = new ExpandoObject(); 
x.AddProperty("NewProp", System.String); 

這很容易嗎?

+0

可能重複[如何設置一個C#4動態對象的屬性,當你在另一個變量的名稱爲(http://stackoverflow.com/questions/ 3033410/how-to-set-a-property-of-ac-sharp-4-dynamic-object-when-you-have-the-name-in-an) – nawfal 2014-07-19 15:55:37

回答

373
dynamic x = new ExpandoObject(); 
x.NewProp = string.Empty; 

或者:

var x = new ExpandoObject() as IDictionary<string, Object>; 
x.Add("NewProp", string.Empty); 
+25

我從未意識到Expando *實現了* IDictionary 。我一直認爲演員會將它複製到字典中。但是,您的帖子讓我明白,如果您更改字典,您還需要更改基礎ExpandoObject!非常感謝 – Dyna 2012-01-27 18:48:22

+0

這是驚人的,我已經證明他們實際上成爲對象的示例代碼的屬性在我的帖子http://stackoverflow.com/questions/11888144/name-variable-using-string-net/ 11893463#11893463,謝謝 – 2012-08-10 02:42:16

4

這裏是一個樣本助手類,它轉換一個Object並返回一個Expando與給定對象的所有公共屬性。


    public static class dynamicHelper 
     { 
      public static ExpandoObject convertToExpando(object obj) 
      { 
       //Get Properties Using Reflections 
       BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; 
       PropertyInfo[] properties = obj.GetType().GetProperties(flags); 

       //Add Them to a new Expando 
       ExpandoObject expando = new ExpandoObject(); 
       foreach (PropertyInfo property in properties) 
       { 
        AddProperty(expando, property.Name, property.GetValue(obj)); 
       } 

       return expando; 
      } 

      public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue) 
      { 
       //Take use of the IDictionary implementation 
       var expandoDict = expando as IDictionary; 
       if (expandoDict.ContainsKey(propertyName)) 
        expandoDict[propertyName] = propertyValue; 
       else 
        expandoDict.Add(propertyName, propertyValue); 
      } 
     } 

用法:

//Create Dynamic Object 
dynamic expandoObj= dynamicHelper.convertToExpando(myObject); 

//Add Custom Properties 
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");