简体   繁体   English

具有公共访问器的自动属性与受保护变量

[英]Auto-property vs. protected variable with public accessors

In some code that I've recently inherited the responsibility for, I've found several instances where the original developer did something like the following: 在我最近继承了职责的一些代码中,我发现了几个实例,原始开发人员做了如下操作:

protected MyEnumerationType _foo;

public MyEnumerationType Foo
{
    get { return _foo; }
    set { this._foo = (MyEnumerationType) value; }
}

This seems unnecessarily verbose to me and I'm curious as to whether there is some advantage to doing this instead of simply using an auto-property: 这对我来说似乎不必要地冗长,我很好奇这样做是否有一些优势,而不是仅仅使用自动属性:

public MyEnumerationType Foo { get; set; }

Am I missing something? 我想念什么吗? Is there some advantage to the first section of code above that I'm not aware of? 我不知道上面代码的第一部分有什么优势吗?

The likelihood is that the original code was written before C# 3.0 was released, which is when auto-implemented properties were introduced. 可能是原始代码是在C#3.0发布之前编写的,这是在引入自动实现的属性时。 In earlier versions of the language, the first approach is the only one that was possible. 在该语言的早期版本中,第一种方法是唯一可能的方法。

In C# 3.0 and later, the main advantage to explicitly defining the backing field is to perform operations on it that are not possible through properties, such as initializing it with a default value (which would otherwise have to be done through a constructor) and declaring it as volatile. 在C#3.0及更高版本中,显式定义后备字段的主要优点是对它执行无法通过属性进行的操作,例如使用默认值初始化它(否则必须通过构造函数完成)并声明它是挥发性的。

This can be advantage, don't know if it's in your domain so, if you think that the class that derives from that class can access the field MyEnumerationType _foo , avoiding in this way (for some reason) access it via property. 可能是一个优势,不知道它是否在您的域中,因此,如果您认为从该类派生的类可以访问字段MyEnumerationType _foo ,则可以通过某种方式避免(出于某种原因)通过属性访问它。

It's hard to say if in your specific context there is some meaning, but, I repeat, there could be meaning described above. 很难说在您的特定上下文中是否存在某些含义,但是,我重复一遍,可能存在上述含义。

For example, if I would have : 例如,如果我有:

public MyEnumerationType Foo
{
    get { return _foo; }
    set { 
           this._foo = (MyEnumerationType) value; 
           TriggerSomething(..);
       }
}

so setting that property I would trigger some actions in my environment, accessing the field directly will help me avoid unnecessary (for architectual decisions) triggering, if I change that field from some child class. 因此,如果我从某些子类中更改了该字段,那么设置该属性后,我将在我的环境中触发一些操作,直接访问该字段将有助于避免不必要的(对于架构决策)触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM