你们觉得哪些更好?
private Point location;
public int LocationX { get { return location.X; } }
public int LocationY { get { return location.Y; } }
Run Code Online (Sandbox Code Playgroud)
要么
private Point location;
public Point Location { get { return location; } }
Run Code Online (Sandbox Code Playgroud)
第二种方法的问题在于,X并且Y可以通过类的客户端进行突变,在这种情况下,客户端不是我想要的.我应该做一个包装,Point所以我可以返回一个不可变的Point?
谢谢
我更喜欢第二种方法,因为X和Y成员不可变(Point是结构,因此是值类型).也就是说,您无法更改位置,因为您无法修改类的Location属性的X或Y属性,因为Point是值成员.如果要更改它,则必须实例化一个新的Point实例.
请看下面的示例,编译器将阻止您更改Location属性的X或Y成员:
class Program
{
private class MyType
{
private readonly Point _location;
public MyType(Point location)
{
_location = location;
}
public Point Location
{
get
{
return _location;
}
}
}
static void Main( string[] args )
{
var someInstance = new MyType (new Point (5, 6));
someInstance.Location.X = 5; // <- compiler error: cannot modify the expression because it is not a variable.
}
Run Code Online (Sandbox Code Playgroud)