有区别吗:
public T RequestedValue { get; set; }
和
public T RequestedValue;
?
取自这段代码:
public class PropertyChangeRequestEventArgs<T>:EventArgs
{
public PropertyChangeRequestEventArgs(T pRequestedValue)
{
RequestedValue = pRequestedValue;
}
public T RequestedValue { get; set; }
}
最佳答案
第一个是 Auto-Implemented Property第二个是 Field .常规Properties公开 Getters 和 Setters 但有一个私有(private)字段来实际存储值:
private int someProperty;
public int SomeProperty
{
get { return someProperty; }
set { someProperty = value; }
}
第一个允许您更改类实现的某些方面而不影响应用程序中的所有其他代码。最重要的一点是,使用属性,可以在不破坏二进制兼容性的情况下进行更改(尽管通常可以在不破坏代码的情况下将字段更改为属性)。如果是公共(public)成员,建议使用属性。 (无耻地盗用了 Snarfblam 的评论)
从属性页面:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
具有支持字段的属性是最灵活的形式,因为它们允许轻松实现诸如 INotifyPropertyChanged
事件之类的东西,用于更新 Model-View-ViewModel 实现中的 UI。
关于C#:我可以删除 "{ get; set; }"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1693875/