简体   繁体   中英

getting property of a class object variable c#

I need to Assign a value to a Variable of one class by its name as string.

that is,

i have a class,

public class Test
{
    public int a = 0; //{ get; set; }
    public int b { get; set; }
    public int c { get; set; }
}

Here, i can set the value to the Test Variables like,

Test test = new Test();
string var1= "b";
// By Using Reflection
PropertyInfo pi= test.GetType().GetProperty(var1);
pi.SetValue(test, Convert.ChangeType(1,pi.PropertyType), null);

so i can get test.b as 1. Likewise i need to set the value for a. How do i accomplish it. Thanks for your time.

Your int a isn't a property, it is a field. Hence, you have to get the FieldInfo using GetField instead of GetProperty :

FieldInfo fi= test.GetType().GetField(var1);
fi.SetValue(test, Convert.ChangeType(1,fi.FieldType));

a is not a property, but a field. You can get it almost the same way, but using other reflection facilities.

FieldInfo a = test.GetType().GetField("a");
int result = (int)a.GetValue(test);

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