我正在尝试根据 EventArg 的位置在某些事件之后设置控件的位置pictureBox1.Location.X = e.X;。
但是,这不起作用Cannot Modify expression because it is not a variable。但我的印象是 x 坐标是一个属性,可以设置。这里发生了什么 ?
因为System.Drawing.Point是值类型,所以当您调用 时pictureBox1.Location,您实际上得到的是Point. 一个全新的对象被构造并填充了 的字段pictureBox1.Location。
因此,编译器试图保护您免于做一些愚蠢的事情,因为更改副本的值不会传播到Location.
因此,正如其他答案中提到的那样,您应该构造一个新的Point并将其分配给该Location属性。
试试这个:
pictureBox1.Location = new Point(e.X, pictureBox.Location.Y);
或者如果您不想构造新变量:
Point location = pictureBox1.Location;
location.X = e.X;
pictureBox1.Location = location;
这是因为Point它是一种值类型,因此您不能只编辑它的一个值,因为它不会传播。它的值被存储,而不是对该值的引用。你不能只是编辑它,你需要再次构建对象。这可以编译,但它绝对不会做任何事情,在任何可能的情况下,所以编译器确保你不会犯这个错误。
这里有些人说的Point是一个值类型,你不能改变它的Xand Y,那种解释会让你很困惑。我在这里发布这个答案是为了帮助你理解为什么你不能改变它Location。那是因为Locationis aProperty返回 aStructure而不是对 an 的引用Object,如果你有一个字段,你可以改变这种方式,如下所示:
public class YourControl : BaseControl {
public Point Location;
}
//Then you can change the Location your way:
yourControl.Location.X = ....
但是,正如我所说,Location它Property返回值类型(结构)的副本,如下所示:
public class YourControl : BaseControl {
private Point location;
public Point Location {
get {
return location;//a copy
}
set {
location = value;
}
}
}
//So when you call this:
yourControl.Location
//you will get a copy of your Location, and any changes made on this copy won't affect
//the actual structure, the compiler needs to prevent doing so.
yourControl.Location.X = ... //Should not be executed...
这不是唯一的情况Location,您可以在所有其他值类型的属性中找到此问题。