Easy:
a.GetType().GetProperty("X").SetValue(a, value);
Note that GetProperty("X")
returns null
if type of a
has no property named "X".
To set property in the syntax you have provided just write an extension method:
public static class Extensions
{
public static void SetProperty(this object obj, string propertyName, object value)
{
var propertyInfo = obj.GetType().GetProperty(propertyName);
if (propertyInfo == null) return;
propertyInfo.SetValue(obj, value);
}
}
And use it like this:
a.SetProperty(propertyName, value);
UPD
Note that this reflection-based method is relatively slow. For better performance use dynamic code generation or expression trees. There are good libraries that can do this complex stuff for you. For example, FastMember.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…