是否可以确保 C# 虚拟属性在派生 类 中具有两个访问器?

Is it possible to ensure C# virtual properties have both accessors in derived classes?

我在 C# 语言规范中看到以下内容。

If the inherited property includes both accessors (i.e., if the inherited property is read-write), the overriding property can include either a single accessor or both accessors.

假设我想确保如果派生 class 覆盖虚拟 属性,它同时具有 getter 和 setter。有没有办法确保这一点,而不必将虚拟 属性 分成两个单独的?

答案是否定的

David 是对的。我认为强迫 child class 覆盖虚拟 属性 违反了 OOP 原则。基础 class 的一个目的是提供可供 child classes 使用的基础实现。如果你告诉你的 children 他们 必须 实施它,那么你作为 parent 不应该提供基本实施(明显的家庭并行意图) .

要强制您的 child 覆盖成员,它必须是 abstract

在此示例中,基础 class 提供默认实现:

// Base Abstract Class
public abstract class Avenger
{
    public virtual string MyVehicle
    {
        get
        {
            if (MyVehicle == null)  // Default the value if it is null
                MyVehicle = "Quinjet";  
            return MyVehicle;
        }
        set; // Allow the child class to set their own vehicle
    }
}

// Derrived class piggy-backs off of the parent's implementation
public class Hulk : Avenger
{}

在此示例中,基础 class 强制 child class 通过不提供他自己的成员之一(使用 摘要)

// Base Abstract Class
public abstract class Avenger
{
    public abstract string MyIdentity { get; }
}

// Not implementing MyIdentity results in compile error
public class Hulk : Avenger
{ }

编译错误:'Hulk'没有实现继承的抽象成员'Avenger.myIdentity.get'

但是对于约翰的观点,parent无法控制child的行为。 这编译:

// Base Abstract Class
public abstract class Avenger
{
    public abstract string MyIdentity { get; }
}

// Derrived class implements abstract member
public class Hulk : Avenger
{
    public override string MyIdentity
    {
        get { throw new NotImplementedException("Won't tell"); }
    }
}