What is the best design I can use to define methods with the same name?

There is such a design problem.

Suppose you have a set of classes that implements similar methods, but not identical ones.

Example: class A has such methods.

void Add(string str);
void Delete(string str);
List<string> GetInfo(string name);

Another class, ClassB has the following methods.

void Add(Dictionary Info);
void Delete(string str);
Dictionary GetInfo(string name);

Thus, the nature of the methods is similar, but the return types / input parameters are different. If I develop an interface to maintain consistency, I can only define the delete operation there. Alternatively, I can think of a set of independent class without any relationship with each other (of course, no interface implementations), but I do not think this is a good design.

  • What is the approach I can use to implement this?
  • . ? , .
+5
5

. :

interface IModifiable<T>
{
  void Add(T Info);
  void Delete(T item);
  T GetInfo(string name);
}
public class MyClass : IModifiable<List<string>>
{
   public void Add(List<string> list)
   { 
      //do something
   }

   public void Delete(List<string> item)   {  }
   public List<string> GetInfo(string name)  {  }
}
+8

, :

interface IFoo<TKey, TValue>
{
    void Add(TKey name, TValue value);
    void Delete(TKey name);
    IEnumerable<TValue> GetInfo(TKey name);
}

, . , , , .

, IDictonary ILookup. , .

+3
public interface IInt<T> {
    void Add(T val);
    void Delete(string str);
    T GetInfo(string name);
}
+1

, ,

public void Detele<T>(T toDelete); //optional : where T 

( , )

, - . , ..Net , StreamReader, ToString ..

, , , .

( ) -.

Add<T,P>(Action<T,P> addingAction, T source, P param) ( addingAction(source,param); );
//this is naive p.Add(q) it can be arbitralily more complicated
aObject.Add( (p,q) => p.Add(q), myObj, myParam);

, . , , . , . - .

I also introduced an implementation that uses an Action delegate. You can easily convert this code to the Expression class, with which you can create your own delegates at runtime (and cache them after initialization, since this is a rather slow process, i.e., Reflection, etc.). I highly recommend abusing delegates and expressions whenever possible.

Take care Lukas

0
source

All Articles