将字符串转换为属性名称

本文关键字:属性 字符串 转换 | 更新日期: 2023-09-27 18:36:56

我有一个名为 AnchorLoadclass 的类,其属性为 diameterthickness 。我在列表中有一个属性列表。现在我想遍历一个列表并将属性值设置为

myanchor.(mylist[0]) = "200";

但它不起作用。我的代码是:

    private void Form1_Load(object sender, EventArgs e)
    {
        AnchorLoadclass myanchor = new AnchorLoadclass();
        var mylist = typeof(AnchorLoadclass).GetProperties().ToList();
        myanchor.GetType().GetProperty(((mylist[0].Name).ToString())) = "200";
        myanchor.thickness ="0.0";
        propertyGrid1.SelectedObject = myanchor;         
    }

将字符串转换为属性名称

正如你忘了在问题中提到的,这行

myanchor.GetType().GetProperty(((mylist[0].Name).ToString())) = "200";

无法编译(请避免不起作用)。你必须这样做:

 // 1. Get property itself:
 String name = "diameter"; // or mylist[0].Name or whatever name
 var propInfo = myanchor.GetType().GetProperty(name);
 // 2. Then assign the value
 propInfo.SetValue(myanchor, 200);

通常,最好的做法是

  // Test, if property exists
  if (propInfo != null) ...
  // Test, if property can be written
  if (propInfo.CanWrite) ...

等。

您应该使用 PropertyInfo 在对象 (myanchor) 上设置属性值 (200),如下所示:

PropertyInfo propertyInfo = myanchor.GetType().GetProperty(((mylist[0].Name).ToString()));
propertyInfo.SetValue(myanchor, 200);