C# 设置私有变量的值

C# set value of private variable

这是我要设置的私有值

 private PhaseList stages;

这是我的测试

    MockRepository mocks = new MockRepository();
        mocks.Stub<UserAction>();
        Game g = new Game(players, cardList);
        Type stage = typeof(PhaseList);
        FieldInfo stinfo = stage.GetField("stages",
        BindingFlags.NonPublic | BindingFlags.Instance);

        PhaseList p = new PhaseList();
        p.add(new DiscardPhase(players[0]));
        p.add(new DiscardPhase(players[0]));
        stinfo.SetValue(g, p);
        g.processUserInput(0, mocks.Stub<UserAction>());

我收到这个错误:

System.NullReferenceException: Object reference not set to an instance of an object.

它指向这一行:

stinfo.SetValue(g, p);

我不明白为什么 stinfo=null;

谁能帮帮我?

您正在尝试获取 PhaseList class 的类型,然后在其中获取一个名为 stages 的私有字段。我假设它没有名为 "stages" 的字段,所以你会得到 null.

做的是一个名为"stages"的字段,在一些other class中,这可能是一个实例的 PhaseList class.

Type stage = typeof(Whatever_Class_Has_The_Stages_Field_In_It);

FieldInfo stinfo = stage.GetField("stages", BindingFlags.NonPublic | BindingFlags.Instance);