在运行时动态添加动态属性

Dynamically adding dynamic properties at runtime

我想添加动态属性并动态地添加到对象。虽然这里回答了一个类似的问题,但使用 ExpandoObject:

Dynamically Add C# Properties at Runtime

虽然上面的答案动态添加了属性,但它并没有满足我的需要。 我希望能够添加变量属性。

我真正想做的是编写一个通用方法,该方法采用 T 类型的对象和 returns 具有该对象所有字段的扩展对象以及更多:

public static ExpandoObject Extend<T>(this T obj)
{
    ExpandoObject eo = new ExpandoObject();
    PropertyInfo[] pinfo = typeof(T).GetProperties();
    foreach(PropertyInfo p in pinfo)
    {
        //now in here I want to get the fields and properties of the obj
        //and add it to the return value
        //p.Name would be the eo.property name
        //and its value would be p.GetValue(obj);
    }

    eo.SomeExtension = SomeValue;
    return eo;
} 

你可以这样做:

public static ExpandoObject Extend<T>(this T obj)
{
    dynamic eo = new ExpandoObject();
    var props = eo as IDictionary<string, object>;

    PropertyInfo[] pinfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo p in pinfo)
        props.Add(p.Name, p.GetValue(obj));

    //If you need to add some property known at compile time
    //you can do it like this:
    eo.SomeExtension = "Some Value";

    return eo;
}

这允许您这样做:

var p = new { Prop1 = "value 1", Prop2 = 123 };
dynamic obj = p.Extend();

Console.WriteLine(obj.Prop1);           // Value 1
Console.WriteLine(obj.Prop2);           // 123
Console.WriteLine(obj.SomeExtension);   // Some Value