动态地将属性添加到`dynamic`类型

时间:2015-01-11 17:20:19

标签: c# reflection reflection.emit system.reflection dynamic-typing

如果我有一个属性信息列表,以及它们来自的对象实例,我该如何创建另一个包含这些属性和值的对象?

e.g。

public dynamic Sanitize<T>(T o)
{
    if (ReferenceEquals(o, null))
    {
        return null;
    }

    var type = o.GetType();

    var propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    dynamic sanitized = new ExpandoObject();

    foreach (var propertyInfo in propertyInfos)
    {
        var name = propertyInfo.Name;
        var value = propertyInfo.GetValue(o, null);

        // Add this property to `sanitized`
    }

    return sanitized;
}

1 个答案:

答案 0 :(得分:2)

您可以将ExpandoObject强制转换为IDictionary<string, object>,然后在运行时将其操作以添加属性:

var sanitized = new ExpandoObject() as IDictionary<string, object>;

foreach (var propertyInfo in propertyInfos)
{
    var name = propertyInfo.Name;
    var value = propertyInfo.GetValue(o, null);
    sanitized.Add(name, value);
}