【问题标题】:Abstract class inheriting from non-abstract in .NET?从.NET中的非抽象继承抽象类?
【发布时间】:2013-06-10 23:15:25
【问题描述】:

我想知道具体(即非抽象)类的子类是否可以是抽象的。在一个虚构的例子中:

public class HistoricallyManaged<SpecificType> 
  { // code to manage history }

public abstract class ComputationalNode<SpecificType>: HistoricallyManaged<SpecificType>
  { // common methods implemented, but some left to concrete classes }

public class Formula<SpecificType>: ComputationalNode<SpecificType> 
  { // code to manage common formula behavior like checking if parameters have been calculated }

public class Variable<SpecificType>: ComputationalNode<SpecificType>  
 { // code to manage common variable behavior like persisting values }

// usage example
public class SomeOtherClass {
  private Formula<int> intFormula;
  private Formula<double> doubleFormula;
  private Variable<int> intVar;
  private Variable<double> doubleVar;
}

在上面的示例中,我想禁止实例化 ComputationalNode 或使用模板绑定来创建像 ComputationalNode 这样的类型,但是我确实希望允许声明 HistoricallyManaged strong> 和其他类型,因此更高层次的实例化必须是可能的,但不能在中间级别。

感谢您的宝贵帮助。

【问题讨论】:

  • 你试过了吗?发生了什么?
  • 那么,它编译了吗?它运行吗?这肯定会给你答案吗?

标签: .net templates generics inheritance abstract-class


【解决方案1】:

当然可以。 object 不是 abstract(尽管 IMO 应该是),所以 每个 abstract class 实际上就是一个例子:

abstract class Foo {} // tada! - note this is implicitly : object

不过,您需要将其进一步子类化为非abstract,然后才能创建它的实例。

但要明确:

class Foo {} // fine
abstract class Bar : Foo {} // fine
class Blap : Bar {} // fine

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2023-04-03
    相关资源
    最近更新 更多