dimanche 11 janvier 2015

Dynamically add properties to `dynamic` type

If I have a list of property infos, and the instance of the object they came from, how can I create another object containing those properties and values?


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





Aucun commentaire:

Enregistrer un commentaire