Here is what I mean:
I need to be able to substitute this ugly looking C# code:
if (attribute.Name == "Name") machinePool.Name = attribute.Value;
else if (attribute.Name == "Capabilities") machinePool.Capabilities = attribute.Value;
else if (attribute.Name == "FillFactor") machinePool.FillFactor = attribute.Value;
into something like this:
machinePool.ConvertStringToObjectField(attribute.Name) = attribute.Value;
There is no ConvertStringToObjectField() method, but I would like to have something like this, if it's possible. I have access to the machinePool object class code, so I can add neccessary code, but I am not sure what code it may be or is it even possible to do in C#.
Yes, you can do this through reflection:
var fieldInfo = machinePool.GetType().GetField(attribute.Name);
fieldInfo.SetValue(machinePool, attribute.Value);
You could also create an extension method to make things easier:
public static void SetField(this object o, string fieldName, object value)
{
var fi = o.GetType().GetField(fieldName);
fi.SetValue(o, value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With