Matching string with class property names
I have a class with let say 5 Properties
Int32 Property1;
Int32 Property2;
Int32 Property3;
Int32 Property4;
Int32 Property5;
Now I only need to set the values โโof three of these properties dynamically. so far ok, but my problem is that I am getting these three Property Names as strings at runtime. Let's say something like this.
List<String> GetPropertiesListToBeSet()
{
List<String> returnList = new List<String>();
returnList.Add("Property1");
returnList.Add("Property3");
returnList.Add("Property4");
retun returnList;
}
So,
List<String> valuesList = GetPropertiesToBeSet();
foreach (String valueToSet in valuesList)
{
// How Do I match these Strings with the property Names to set values
Property1 = 1;
Property3 = 2;
Property4 = 3;
}
+3
source to share
2 answers
You can do something like this. Properties are your class
Properties p = new Properties();
Type tClass = p.GetType();
PropertyInfo[] pClass = tClass.GetProperties();
int value = 0; // or whatever value you want to set
foreach (var property in pClass)
{
property.SetValue(p, value++, null);
}
+6
source to share
Let's say that the name of the class containing them is Properties
. You can use a method GetProperty()
to get PropertyInfo
and then a method SetValue()
:
Properties p = new Properties();
Type t = p.GetType(); //or use typeof(Properties)
int value = 1;
foreach (String valueToSet in valuesList) {
var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance; //because they're private properties
t.GetProperty(valueToSet, bindingFlags).SetValue(p, value++); //where p is the instance of your object
}
+3
source to share