简体   繁体   中英

Convert a string to a property name

I have a class named AnchorLoadclass with properties like diameter , thickness . I have got a list of properties in a list. Now I want to iterate through a list and set value of properties as:

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

But it's not working. My code is as:

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

As you forgot to mention in the question, the line

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

doesn't compile (please avoid doesn't working ). You have to do this:

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

Often, it is a good practice to

  // Test, if property exists
  if (propInfo != null) ...

  // Test, if property can be written
  if (propInfo.CanWrite) ...

etc.

You should use PropertyInfo to set the property value (200) on the object (myanchor) as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM