【发布时间】:2013-03-11 03:59:30
【问题描述】:
在这个例子中 Foo.Something 和 Bar.Something 之间有什么有效的区别吗?
class Foo
{
public string Something;
}
class Bar
{
public string Something{get; set;}
}
class Program
{
static void Main(string[] args)
{
var MyFoo = new Foo();
MyFoo.Something = "Hello: foo";
System.Console.WriteLine(MyFoo.Something);
var MyBar = new Bar();
MyBar.Something = "Hello: bar";
System.Console.WriteLine(MyBar.Something);
System.Console.ReadLine();
}
}
AFAIK 他们的行为完全相同。如果他们这样做,为什么不使用 Foo 中的普通字段? 在 java 中,我们使用 setter 来强制执行新的不变量而不破坏代码和 getter 以返回安全数据,但在 c# 中,您始终可以将 Foo 重写为:
class Foo
{
private string _Something;
public string Something
{
get {
//logic
return _Something;
}
set {
//check new invariant
_Something = value;
}
}
}
而且旧代码不会被破坏。
【问题讨论】: