将String与Class属性Names匹配

时间:2014-12-05 13:59:37

标签: c# reflection

我有一个类,让我们说5个属性

Int32 Property1;
Int32 Property2;
Int32 Property3;
Int32 Property4;
Int32 Property5;

现在我必须动态设置这三个属性的值。到目前为止还可以,但我的问题是我在运行时将这三个属性名称作为字符串。 让我们说,像这样......

List<String> GetPropertiesListToBeSet()
{
   List<String> returnList = new List<String>();
   returnList.Add("Property1");
   returnList.Add("Property3");
   returnList.Add("Property4");
   retun returnList;
}

所以现在,

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

2 个答案:

答案 0 :(得分:6)

你可以这样做。属性是你的类

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

答案 1 :(得分:4)

假设包含它们的类的名称是Properties。您可以使用GetProperty()方法获取PropertyInfo,然后使用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
}