正确使用封装在类内部属性中的字段 [英] Correct use of fields that are encapsulated in properties inside a class

查看:126
本文介绍了正确使用封装在类内部属性中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应在哪种情况下更改类方法/属性内的私有字段:

Which scenario should I use for changing private fields inside class methods/properties:

public class Example
{
 private int intVar = 0;
 private string stringVar = string.Empty;

 public int IntVar
 {
  get { return this.intvar; }
  set { this.intvar = value; }
 }

 public string StringVar 
 {
  get { return this.stringVar ; }
  set { this.stringVar = value; }
 }

 private void SomeMethod()
 {
  //change fields in this way:
  this.intVar = 50;
  this.stringVar = "changed";
  //or that way(through properties):
  this.IntVar = 50;
  this.StringVar = "changed";
 }
}

也许在此示例中没有区别,但是如果有人向属性中添加了额外的代码,并且通过属性更改字段会改变其他内容?

Maybe in this example it makes no difference, but what if someone add extra code to properties, and changing fields through properties will change some other things?

您能说哪种方法更好,或者实际上没有什么区别?

Can you say which way is better, or it really makes no difference?

我知道从C#3.0开始,我可以编写自动实现的属性,但这是C#2.0。

I know that since C# 3.0 I can write auto-implemented properties, but this is C# 2.0.

推荐答案

我会说使用属性通常更好。如果getter和setter很简单,则无论如何它们可能在运行时被抖动内联。正如您所说,也许会对属性代码进行其他更改。

I'd say using a property is usually better. If the getters and setters are simple, they might get inlined by the jitter at runtime anyway. And as you said, maybe other changes will be made to the property code.

常见的更改是通过实现INotifyPropertyChanged来添加更改通知。如果您直接设置字段,则听众将不会收到通知。

A common change is adding change notifications by implementing INotifyPropertyChanged. Listeners would not get notified if you set the fields directly, then.

我更喜欢我的类使用其自己的公共接口而不是内部接口。对我来说例外是当我明确不希望有任何副作用时。不过,这种情况很少。

I prefer my classes to use their own public interface rather than internals. An exception for me is when i explicitly do not want any of the side effects. That is rarely the case though.

这篇关于正确使用封装在类内部属性中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆