简体   繁体   English

c#根据字符串设置变量值

[英]c# set variable value based on string

I have a class with a list of variables (shortened to one "a" here) - I'm trying to create a way to populate a variable based on two string inputs, so I can just use, for instance:我有一个包含变量列表的类(这里缩短为一个“a”) - 我正在尝试创建一种基于两个字符串输入填充变量的方法,因此我可以使用,例如:

SET_VAL("a", "value_for_a")

Which I'd like to get the MessageBox showing just "value_for_a"我想让 MessageBox 只显示“value_for_a”

but I'm tripping up trying to use reflection, I'm sure this is possible, I know it's possible to get a value from a variable using a string to find it's name, cos every time I search for this that's all I seem to get, but why doesn't the following work?但是我在尝试使用反射时绊倒了,我确定这是可能的,我知道可以使用字符串从变量中获取一个值来查找它的名称,因为每次我搜索这个时,我似乎就是这样得到,但为什么以下不起作用? The method SetValue is asking for objects as parameters when I just want to pass two strings?当我只想传递两个字符串时, SetValue方法要求将对象作为参数?

public class MySystem_SubsNote
   {
       public string a;

       public void SET_VAL(string mytype, string myvalue)
       {
            this.GetType().GetField(mytype).SetValue(myvalue);
            MessageBox.Show(a);
       }
   }
    
         

As mentioned from Lasse in the comments SetValue expects two parameters, the first being the instance of which to set the value, the second the new value.正如 Lasse 在评论中提到的SetValue需要两个参数,第一个是要设置值的实例,第二个是新值。 So this should do it:所以这应该这样做:

public void SET_VAL(string mytype, string myvalue)
{
    this.GetType().GetField(mytype).SetValue(this, myvalue);
    MessageBox.Show(a);
}

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

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