简体   繁体   English

获取类对象变量c#的属性

[英]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. 所以我可以将test.b设为1。同样,我需要为a设置值。 How do i accomplish it. 我该怎么做。 Thanks for your time. 谢谢你的时间。

Your int a isn't a property, it is a field. 您的int a不是属性,而是一个字段。 Hence, you have to get the FieldInfo using GetField instead of GetProperty : 因此,您必须使用GetField而不是GetProperty获取FieldInfo

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

a is not a property, but a field. a不是属性,而是字段。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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