抽象属性是否会创建私有支持字段? [英] Does an abstract property create a private backing field?
问题描述
简单的问题:抽象属性是否会创建私有支持字段?示例:
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.
推荐答案
不,它没有.我刚刚用以下课程进行了测试:
No it doesn't. I just tested with the following class:
public abstract class Class1
{
public abstract string TestStringAbstract { get; set; }
public string TestString { get; set; }
}
并在 Reflector 中对其进行反编译.这是生成的代码:
and decompiled it in Reflector. This was the generated code:
public abstract class Class1
{
// Fields
[CompilerGenerated]
private string <TestString>k__BackingField;
// Methods
protected Class1()
{
}
// Properties
public string TestString
{
[CompilerGenerated]
get
{
return this.<TestString>k__BackingField;
}
[CompilerGenerated]
set
{
this.<TestString>k__BackingField = value;
}
}
public abstract string TestStringAbstract { get; set; }
}
如您所见,只为具体属性生成了一个支持字段.抽象的留作定义.
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.
这篇关于抽象属性是否会创建私有支持字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!