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

时间:2016-12-07 16:45:02

标签: c# expandoobject

我想动态地添加动态属性到对象。虽然这里回答了一个使用ExpandoObject

的类似问题

Dynamically Add C# Properties at Runtime

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

我真正希望做的是编写一个泛型方法,该方法接受类型为T的对象,并返回一个包含该对象的所有字段的扩展对象以及更多:

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;
} 

1 个答案:

答案 0 :(得分:4)

你可以这样做:

SELECT  COUNT(*) totalCount
FROM    go_J a 
        LEFT JOIN go_H b
            ON a.GoCode = b.GoCode 
WHERE   b.GoCode IS NULL

这允许您这样做:

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;
}