如何在C#中的类中动态设置变量的值?

Dim*_*oof -2 c# reflection

我正在尝试做这样的事情:

public class MyClass()
{
  private void SetAValiable(int boolNumber)
  {
    bool b1 = false;
    bool b2 = false;

    ("b" + boolNumber) = true;
  }
}
Run Code Online (Sandbox Code Playgroud)

我试过这个但是不断从GetProperty调用中得到一个null:

Type myType = typeof(MyClass);
PropertyInfo pinfo = myType.GetProperty("b" + boolNumber);
pinfo.SetValue(myType, true, null);
Run Code Online (Sandbox Code Playgroud)

任何人都有任何想法如何让这个工作?

谢谢!

Ser*_*rvy 7

使用数组,而不是反射:

public class MyClass()
{
    private void SetAValiable(int boolNumber)
    {
        bool[] b = new bool[2]; //will default to false values
        b[boolNumber] = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您尝试的那样,无法使用反射来访问局部变量.他们需要成为一个选项的领域,但即便如此,它仍然不是正确的选择.