【问题标题】:When defining an abstract class, can you force a child to define a property/method defined in a parent interface?定义抽象类时,是否可以强制子类定义父接口中定义的属性/方法?
【发布时间】:2020-06-18 05:41:01
【问题描述】:

考虑以下类定义。

public abstract class FooBase : IBar
{
  public int Value {get; set;}
  public string ToString() 
  {
    //Return a string.
  }
}

public interface IBar 
{
  int Value;
  string ToString();
}

FooBase 是一个提供IBar 接口实现的基类。

作为抽象类,FooBase 不能直接实例化。因此,另一个类必须派生自这个类才能使用。

现在,考虑您需要像 FooBase 这样实现 IBar 接口的对象的场景,但是,对于某个特定成员 IBar,您需要 FooBase 的子代来实现它,而不是 @987654329 @ 自己。

有没有办法实现/寻址抽象类中的成员,如FooBase,派生自IBar,这样FooBase 的任何子级都必须实现来自IBar 的单个成员,而不是而不是依赖FooBase的基本实现?

我认为没有,因为编译器告诉我们不允许声明像 public abstract int Value 这样的值,但我认为值得询问和验证。但是,也许我错了,如果是这样,是否有适当的方法强制我的基类的子实现从我的基类的父接口实现成员?

【问题讨论】:

  • public abstract int Value { get; set; }?
  • 语法决定一切!呃,我只是今天不在我的 A-game 上。我知道这是可行的。

标签: c# access-modifiers


【解决方案1】:

假设没有,因为编译器告诉声明不允许像 public abstract int Value 这样的值

当然可以,这样编译得很好:

interface IBar
{
    int Foo { get; set; }
    string Blah();
}

abstract class Base: IBar
{
    public abstract int Foo { get; set;}
    public string Blah() => null;
}

现在:

class Derived: Base
{
     //must implement Foo
}

顺便说一句,您的代码无法编译,您无法在接口中定义字段。

【讨论】:

    【解决方案2】:

    这编译得很好:

    public abstract class FooBase : IBar
    {
        public abstract int Value { get; set; }
    }
    
    public interface IBar
    {
        int Value { get; }
    }
    

    任何派生自 FooBase 的类都必须覆盖 Value:

    public class Concrete : FooBase
    {
        public override int Value { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 2013-03-04
      • 2014-10-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      相关资源
      最近更新 更多