本文介绍了抽象属性是否创建私有支持字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:抽象属性是否会创建一个私有后备字段?示例:

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; }
}

并将其反编译为。这是生成的代码:

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.

这是合乎逻辑的,因为该属性必须由任何子类覆盖,因此没有必要创建支持字段永远无法访问(因为您永远无法访问abstract属性)。

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).

另一方面,将创建 virtual 属性一个后备字段,并且任何使用自动实现的替换覆盖该属性的类都将在该类的级别上创建其自己的后备字段。

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.

这篇关于抽象属性是否创建私有支持字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 19:58