mardi 15 février 2022

How to abstract interface method whose param is derived-class-dependent in C#?

I have two version of data manager, and an interface to abstract these two managers. All these two managers take the data's description as string, hiding the specific data structure.

Now I need to add a method with a param of Action<Item> (rather than Action<string> with string stores the description), this action is passed to SDK which cannot be modified.

In this case, the Action<Item> varies according to the specific implementation of Item. How to add this method in C# way?


Here is the example

  1. The interface of different data manager
// the interface
interface IContentManager
{
    void UpdateProduct(string id, string productDescription);

    // TODO: public void ApplyForAll(Action<???> op)
}
  1. The first version of data manager based on a database SDK

The database SDK provides these classes which cannot be modified

class ProductItem { }
class ProductDBWriter
{
    // this method cannot be modified
    public void ApplyForAll(Action<ProductItem> op) { }
}

The data manager based on database SDK

class DBContentManager
{
    void UpdateProduct(string id, string productDescription) { }

    public void ApplyForAll(Action<ProductItem> op)
    {
        _writer.ApplyForAll(op);
    }

    private ProductDBWriter _writer;
}
  1. The second version of data manager, a lightweight version
class ProductItemSlim { }

class SlimContentManager
{
    void UpdateProduct(string id, string productDescription) { }

    // TODO: public void ApplyForAll(Action<???> op)
}

The question is: what is the C# way to abstract the ApplyForAll method?

Aucun commentaire:

Enregistrer un commentaire