通过其[“ String name”]获取变量(int),然后更改其值

时间:2019-03-02 06:40:43

标签: c#

我有一个存储在名为“变量”的类中的变量:

class variables { public static int var1 = 0;  }

////////////////////////////////////////////////////////

如果我想从另一个类中获取其值,请致电:

  var YY= "variable.var1";
  var ZZ= (int)this.GetType().GetField(YY).GetValue(this);

问题是我想在上面做一个镜子 我不想只阅读内容并使用它,我想更改变量值本身。

这是我的办法,但无法实现:(未发现工作恐怖)

string punto1 =  "variables.var1";

valor1 = 999;

var motherclass = Type.GetType(punto1);

//////////

var AA= motherclass.GetType().GetProperty(punto1);

AA.SetValue(motherclass.GetType(), valor1, null);

/////////// 预先感谢,此页面动摇。

1 个答案:

答案 0 :(得分:0)

我不确定您要达到什么目的,但是请检查下面的代码并确定是否要寻找它:

namespace TestApp
{
  class Program
  {

    public class demo
    {
      public int int001 { get; set; }
      public int int002 { get; set; }
      public int int003 { get; set; }
    }

    public static void SetValue(object classInstance, string propertyName, int value)
    {
      PropertyInfo propertyInfo = classInstance.GetType().GetProperty(propertyName);
      propertyInfo.SetValue(classInstance, value);
    }

    static void Main(string[] args)
    {
        demo x = new demo { int001 = 10 };
        Console.WriteLine(x.int001);
        SetValue(x, "int001", 11);
        Console.WriteLine(x.int001);
    }
  }
}

在这里,我定义了一个具有multipe int属性的类,然后定义了一个以字符串名称设置int属性(NB!不是字段)的方法。然后使用该方法设置一个值。控制台输出显示方法调用之前和之后的属性值。