将String与Class属性Names匹配

use*_*020 3 c# reflection

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

Int32 Property1;
Int32 Property2;
Int32 Property3;
Int32 Property4;
Int32 Property5;
Run Code Online (Sandbox Code Playgroud)

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

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

所以,现在,

 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;
 }
Run Code Online (Sandbox Code Playgroud)

Pan*_*kaj 7

你可以做这样的事情.属性是你的班级

        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);
        }
Run Code Online (Sandbox Code Playgroud)