Concrete types in class implementation when using interface

Consider the following code example:

interface IData {
  int Count();
}

interface IOperations {
  IData Foo();
  double Bar(IData a);
}

class Data1 : IData {
  public int Count() { return 37; }
  public double SomethingElse { get; set; }
}

class Ops1 : IOperations 
{
  public Data1 Foo() { return new Data1(); } // want to return specific type here
  public double Bar(Data1 x) { ... } // want to get specific type here
                                     // and not use operator as everywhere
}

// more definitions of classes Data2, Ops2, Data3, Ops3, ...

// some code:
Ops1 a = new Ops1();
Data1 data = a.Foo(); // want Data1 here not IData!
double x = a.Bar(data);

I could, of course, just use public IData Foo() { return new Data1(); }:

// some code
Ops1 a = new Ops1();
Data1 data = a.Foo() as Data1;

but with aseverywhere, the code quickly becomes confusing.

I wonder if there is a good design template to achieve this in a clear and powerful way?

Edit: It is important that operating systems and data have a common base class:

List<IOperations> ops = ...;
List<IData> data = ...;
List<double> result = ...;
for(int i=0; i<ops.Count; i++) 
  result[i] = ops[i].Bar(data[i]);

So, for the case of the return type, I am surprised that this is forbidden because I meet the requirements of the interface. In the case of parameters, some additional (template) layer may be required.

+3
source share
1 answer

You can use generics:

interface IOperations<T> where T: IData
{ 
  T Foo();
  double Bar(T a);
}

class Ops1 : IOperations<Data1>
{
    public Data1 Foo() { return new Data1(); }
    public double Bar(Data1 x) { /* ... */  } 
}
+5
source

Source: https://habr.com/ru/post/1759666/


All Articles