Cannot modify the return value because it is not a variable

前端 未结 7 1745
庸人自扰
庸人自扰 2020-12-11 19:27

I have a class called BaseRobot:

  var robot2 = new BaseRobot(0, 0, 0);
  private Point mHome;
  public Point Home
  {
      get { return mHome;         


        
7条回答
  •  天命终不由人
    2020-12-11 19:33

    I've met somewhere this good explanation (I'll adapt it for this current case):

    It's a bad part of the C# design.

    Internally, stuff like robot2.Home is implemented as properties, so when you try assign a value to Home.X, a get-function for Home gets called under the hood (and this is where "Cannot modify the return value of .." goes from). When this is done, you can't assign into an individual member (X) of the Point struct, but have to assign the entire struct.

    So in C#, you need to read the value out into a Point and then modify it:

    robot2.Home = robot2.Home + new Point (deltaX, deltaY);
    

    Or (if we don't interested in previous value (as in this case)) just assign it to new one:

    robot2.Home = new Point (1f, 5f);
    

    PS: Of course, you also need to add a setter for the Home property (as it is mentioned in other answers).

提交回复
热议问题