Difference between properties and variables
class MyClas
{
public System.Windows.Point p;
public void f()
{
p.X = 0;
}
}
This code works perfectly.
At the same time this one causes compilation error ("Cannot modify the return value of p because it is not a variable"):
class MyClas
{
public System.Windows.Point p {get; set;}
public void f()
{
p.X = 0;
}
}
开发者_开发知识库
What's the difference?You're using a mutable struct which is evil.
Your problem is that a property returns a copy of the struct, and not a reference to the original field. So your modifications would only affect the copied struct.
In some simple cases(calling setters) the compiler catches your mistake. In complex cases(calling of a method which mutates the struct) the compiler doesn't catch it and your code will silently fail(i.e. the copy gets modified and the original remains unchanged).
The workaround is using p=new Point(x,y)
精彩评论