使用私有还是使用属性?C#
请注意,下面的代码是在一个类中的单个类使用私有还是使用属性?C#,c#,properties,private,C#,Properties,Private,请注意,下面的代码是在一个类中的单个类 private string _fee; private string _receipt; public string Fee { get { return _fee; } private set { _fee = value; } } public string Receipt { get { return _receipt; } private set { _receipt = value;} } public M
private string _fee;
private string _receipt;
public string Fee
{
get { return _fee; }
private set { _fee = value; }
}
public string Receipt
{
get { return _receipt; }
private set { _receipt = value;}
}
public MyValue(string fee, string receipt) : this()
{
_fee = int.Parse(receipt).ToString();
_receipt = receipt;
}
正如你所见,我的财产不起任何作用,所以我应该使用它
_fee = int.Parse(fee).ToString();
_receipt = receipt;
或
我将始终使用属性-它为您提供了更大的灵活性:
- 如果需要,您可以稍后创建更详细的getter和setter方法
- 您可以在getter和setter上指定不同的可见性
- 如果需要,可以定义虚拟属性并重写子类中的虚拟属性
- 可以对属性使用数据绑定,但不能对字段使用数据绑定
Marc使用属性,如果您使用的是C#3,则应使用自动实现的属性,如:
public string Fee
{
get; private set;
}
public string Receipt
{
get; private set;
}
public MyValue(string fee, string receipt) : this()
{
this.Fee = int.Parse(fee).ToString();
this.Receipt = receipt;
}
在这种情况下,这并不重要,只要您在整个代码中保持一致 但是,如果属性被标记为
virtual
,那么在构造函数中访问它们不是一个好主意,最好直接使用字段。这是因为属性的行为可能被重写,并且基类可能会调用破坏代码
编辑:为了澄清,我只是指OP示例中方法的差异。marc_s给出了一些很好的观点,说明为什么属性在大多数情况下都是有利的。我总是直接使用成员 这是因为您可能在setter中实现无法从构造函数中正确运行的代码,因为其他一些字段没有初始化
如果像womp提到的那样属性是虚拟的,情况可能会更糟。哦,这是我在ReSharper中使用的第一个脚本。我就是喜欢+1,但我会在您的第一点和反射注释中添加“不破坏二进制兼容性”。否则你也可以重新考虑一个私有字段。我开始怀疑c#编译器是否应该允许公共字段。似乎没有理由使用它们。
public string Fee
{
get; private set;
}
public string Receipt
{
get; private set;
}
public MyValue(string fee, string receipt) : this()
{
this.Fee = int.Parse(fee).ToString();
this.Receipt = receipt;
}