简体   繁体   English

向 ExpandoObject 动态添加属性

[英]Dynamically adding properties to an ExpandoObject

I would like to dynamically add properties to a ExpandoObject at runtime.我想在运行时向 ExpandoObject 动态添加属性。 So for example to add a string property call NewProp I would like to write something like因此,例如要添加一个字符串属性调用 NewProp 我想写一些类似的东西

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

Is this easily possible?这容易吗?

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

Alternatively:或者:

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

As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/正如 Filip 在这里解释的那样 - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/

You can add a method too at runtime.您也可以在运行时添加方法。

x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();

Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given 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);
            }
        }

Usage:用法:

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

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

This is the best solution I've found.这是我找到的最佳解决方案。 But be careful with that.但要小心。 Use exception handling because it might not work on all of the cases使用异常处理,因为它可能不适用于所有情况

public static dynamic ToDynamic(this object obj)
{
    return JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(obj));
}

//another nice extension method you might want to use //你可能想使用的另一个不错的扩展方法

    public static T JsonClone<T>(this T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", nameof(source));
        }

        var serialized = JsonConvert.SerializeObject(source);
        return JsonConvert.DeserializeObject<T>(serialized);
    }

i think this add new property in desired type without having to set a primitive value, like when property defined in class definition我认为这在所需类型中添加新属性而无需设置原始值,就像在类定义中定义的属性一样

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

This is the best solution I've found.这是我找到的最佳解决方案。 But be careful with that.但要小心。 Use exception handling because it might not work on all of the cases使用异常处理,因为它可能不适用于所有情况

    public static dynamic ToDynamic(this object obj)
    {
        return JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(obj));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM