Is there a way to force a derived class to impleme

2019-05-21 01:59发布

I have this abstract class:

public abstract class Task
{
  public string ID {get; set;}
  public string Name {get; set;}
  public abstract class Options{};

  public abstract void Execute();
}

I have other classes extending this class:

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

I'd like each derived class to implement their own Options class so they can have their own parameters.

So Search class have to implement it's own Options class with the properties it needs, such as "includesubfolders", "casesensitive", etc..

Meanwhile Move task can implement it's own: "overwrite", etc..

Making properties and methods abstract in an abstract class force derived classes to implement their own but defining a nested abstract class or an interface in the same class does not force it's derived classes implement their own.

I can define each property individually in each derived class but that defeats the purpose since I like to query the properties in Task.Options later in the Execute method.

I tried dynamic object as well, but that brought whole other issues.

2条回答
倾城 Initia
2楼-- · 2019-05-21 02:30

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.

查看更多
放我归山
3楼-- · 2019-05-21 02: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");
    }
}
查看更多
登录 后发表回答