抽象属性是否会创建私有支持字段?
简单的问题:抽象属性是否会创建私有支持字段?示例:
public abstract Name { get; set; }
这会创建一个私有支持字段吗?我想强制派生此属性的任何类使用它们自己的支持字段,而不是编译器创建的支持字段。
Simple question: does an abstract property create a private backing field? Example:
public abstract Name { get; set; }
Will this create a private backing field? I want to force any class that derives this property to use their own backing field, not one that's created by the compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,没有。我刚刚使用以下类进行了测试:
并在 Reflector 中对其进行了反编译。这是生成的代码:
正如您所看到的,只为具体属性生成了一个支持字段。抽象的被留下来作为定义。
这在逻辑上是有意义的,因为该属性必须被任何子类覆盖,因此创建一个无法访问的支持字段是没有意义的(因为您无法访问抽象属性)。
另一方面,虚拟属性将创建一个支持字段,并且任何使用自动实现的替换覆盖该属性的类都将在该类的级别创建自己的支持字段。
No it doesn't. I just tested with the following class:
and decompiled it in Reflector. This was the generated code:
As you can see only a single backing field was generated for the concrete property. The abstract one was left as a definition.
This makes logical sense since the property must be overridden by any child class there is no point in creating a backing field that there would be no way of ever accessing (since you can't ever access the abstract property).
On the other hand a virtual property will create a backing field and any class that overrides the property with an auto-implemented replacement will create its own backing field at that class's level.
不。由于它是抽象的,类实现者必须实现该属性。如果实现者以这种方式声明它,那么是的,它是一个带有隐藏成员来保存实际值的自动属性。
No. Since it's abstract, the class implementer must implement the property. If the implementer declares it that way, then Yes, it's an automatic property with a hidden member to hold the actual value.
第一个属性声明不
和
创建支持字段。它只是创建一个抽象属性(有点像接口方法声明),它必须由任何非抽象继承类实现。
第二个声明是一个自动属性,它创建一个支持字段。它实际上是编译器语法糖的简写:
There's a difference between:
and
The first property declaration doesn't create a backing field. It just creates an abstract property (kind of like an interface method declaration), which has to be implemented by any non-abstract inheriting class.
The second declaration is an auto-property, which DOES create a backing field. It's actually compiler syntactic sugar shorthand for: