简体   繁体   English

从非抽象类继承时要求重写属性

[英]Require a property to be overridden when inheriting from a non-abstract class

Is there a way to require a property to be overridden in a derived class when base class is not abstract? 当基类不是抽象时,是否有一种方法要求在派生类中重写属性? For example: 例如:

public abstract class BaseClass
{
    protected abstract string Test {get;}
}

internal class FirstClass : BaseClass
{
    protected override string Test => "First Class";
    // Methods common to FirstClass and SecondClass
}

internal class SecondClass : FirstClass
{
    protected override string Test => "Second Class"
}

Is there a way to force property test in FirstClass to be overridden if any class inherits from FirstClass ? 如果有任何类从FirstClass继承,是否有办法强制FirstClass属性test被覆盖?

There is practical need for this (maybe not a big one) is that while logging information, we want to log source of error (class name etc.), therefore we want to force all leaf derived class to override certain properties. 实际需要(可能不是很大)的是,在记录信息时,我们要记录错误源(类名等),因此我们想强制所有叶派生类重写某些属性。

Is there a way to require a property to be overridden in a derived class when base class is not abstract? 当基类不是抽象时,是否有一种方法要求在派生类中重写属性?

(The original question asks about fields. Fields may not be overridden at all; you meant "property", not "field".) (原始问题询问字段。字段可能根本不会被覆盖;您的意思是“属性”,而不是“字段”。)

No. 没有。

Whether a derived class chooses to override or not is an implementation detail that is up to the author of that derived class, who knows more about the business domain of that class than the author of the base class knows. 派生类是否选择重写取决于实现细节,该实现细节取决于该派生类的作者,后者比该基类的作者更了解该类的业务领域。

The only way to make a member that must be overridden is to make it abstract. 使成员必须被覆盖的唯一方法是使其成为抽象。

It is legal to override with an abstract. 用摘要覆盖合法的。 This would be legal, for instance: 例如,这将是合法的:

abstract class BaseClass
{
    protected virtual string Test => "Base";
}
abstract class FirstClass : BaseClass
{
    // override abstract is slightly unusual but legal
    protected override abstract string Test { get; }
    // Concrete derived classes must override
}
class SecondClass : FirstClass
{
    protected override string Test => "Second Class"
}

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

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