我有一个名为BaseRobot的类:
var robot2 = new BaseRobot(0,0); private Point mHome; public Point Home { get { return mHome; } }
这就是创建原始住宅的地方,我想在program.cs中创建一个新住宅.我有以下代码,但它不起作用,它提出错误说
Cannot modify the return value becasue it is not a variable.
码:
robot2.Home.X = 1 robot2.Home.Y = 5; { Console.WriteLine("===New robot at specified home position==="); StringBuilder ab = new StringBuilder(); ab.AppendFormat("Robot#2 has home at <{0},{0}>.\r\n ",robot2.Home.X,robot2.Home.Y); ab.AppendFormat("It is facing {0} ",robot2.Orientation); ab.AppendFormat("and is currently at <{0},{0}>.\r\n",robot2.Position.X,robot2.Position.Y); Console.WriteLine(ab.ToString()); }
如何为x和Y分配新值?
解决方法
您需要直接设置Home属性,通常最好创建一个新的Point对象…
robot2.Home = new System.Drawing.Point(1,5);//x,y
此外,为了允许您需要将一个set访问器应用于您的Home属性…
public Point Home { get { return mHome; } set { mHome = value; } }
如果你想了解更多信息,为什么编译器不会让你直接赋予X属性值,那么检查一下answers over here