Is there a way to force a derived class to implement an abstract class or an interface nested in base class?

雨燕双飞 提交于 2019-12-06 08:43:52

You can use a generic

public abstract class Options{};

public class CopyOptions : Options
{
}

public abstract class Task<T> where T : Options
{
  public string ID {get; set;}
  public string Name {get; set;}

  public T Options { get; set; }

  public abstract void Execute();
}

public class Copy : Task<CopyOptions>
{
    public override void Execute()
    {
        Console.Write("running");
    }
}

You can't enforce a nested class implementation, but you could add a property for the Options:

public abstract class Task
{
  public string ID {get; set;}
  public string Name {get; set;}
  public Options Options {get; set;}
  public abstract void Execute();

  public abstract class Options{};
}

However there's no way to enforce that the implementation of the Options class be nested within the class that implements Task.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!