【发布时间】:2015-01-11 17:20:18
【问题描述】:
如果我有一个属性信息列表,以及它们来自的对象的实例,我如何创建另一个包含这些属性和值的对象?
例如
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;
}
【问题讨论】:
标签: c# reflection reflection.emit system.reflection dynamic-typing