动态将属性添加到ExpandoObject


Answers:


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

或者:

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

32
我从未意识到Expando 实现 IDictionary <string,object>。我一直认为演员表可以将其复制到字典中。但是,您的帖子使我明白,如果您更改字典,那么您还将更改基础的ExpandoObject!非常感谢
Dynalon 2012年

3
得到Error 53 Cannot convert type 'System.Dynamic.ExpandoObject' to 'System.Collections.Generic.IDictionary<string,string>' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
TheVillageIdiot

24
IDictionary<string, object>,不是IDictionary<string, string>
Stephen Cleary 2012年

3
@ user123456:属性名称始终是字符串;他们不可能是动态的。如果“动态”是指“直到运行时才知道”,则必须使用第二个示例。如果按“是动态的”表示属性是动态的,那很好。对于任何一个示例,具有动态值都可以正常工作。
史蒂芬·克利西

3
重要的是要注意,在进行强制转换时IDictionary,请勿将其dynamic用作变量类型。
user3791372


14

这是一个示例帮助器类,该类可转换对象并返回具有给定对象的所有公共属性的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");

11
“ var expandoDict =作为IDictionary的expando;” 此行需要更改为“ var expandoDict = expando as IDictionary <String,object>;”。
乔姆·乔治

0

我认为这可以按需要的类型添加新属性,而无需设置原始值,例如在类定义中定义属性时

var x = new ExpandoObject();
x.NewProp = default(string)

5
嗨,Morteza!纯代码的答案可以解决问题,但是如果您解释它们的解决方法,它们将更加有用。社区需要理论和代码,才能充分理解您的答案。
RBT
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.