我可以将派生类中的这些方法替换为基类中的方法吗?

Sam*_*tar 2 c#

我有这样的方法:

   public void AddOrUpdate(Product product)
    {
        try
        {
            _productRepository.AddOrUpdate(product);
        }
        catch (Exception ex)
        {
            _ex.Errors.Add("", "Error when adding product");
            throw _ex;
        }
    }


    public void AddOrUpdate(Content content)
    {
        try
        {
            _contentRepository.AddOrUpdate(content);
        }
        catch (Exception ex)
        {
            _ex.Errors.Add("", "Error when adding content");
            throw _ex;
        }
    }
Run Code Online (Sandbox Code Playgroud)

加上更多只在传递给它们的类中有所不同的方法.

有没有什么方法可以在基类中编写这些方法而不是在每个派生类中重复该方法?我正在考虑基于泛型的东西,但我不确定如何实现,也不确定如何传入_productRepository.

仅供参考,这是_productRepository和_contentRepository的定义方式:

    private void Initialize(string dataSourceID)
    {
        _productRepository = StorageHelper.GetTable<Product>(dataSourceID);
        _contentRepository = StorageHelper.GetTable<Content>(dataSourceID);
        _ex = new ServiceException();
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*der 5

是的你可以.

简单的方法是使用接口和继承.紧耦合

另一种方法是依赖注入.失去耦合,更可取.

另一种方法是使用泛型如下:

public void AddOrUpdate(T item ,V repo) where T: IItem, V:IRepository
{ 
  repo.AddOrUpdate(item)
}


class Foo
{
    IRepository _productRepository;
    IRepository _contentRepository

    private void Initialize(string dataSourceID)
    {
        _productRepository = StorageHelper.GetTable<Product>(dataSourceID);
        _contentRepository = StorageHelper.GetTable<Content>(dataSourceID);
        _ex = new ServiceException();
    }

    public void MethodForProduct(IItem item)
    {
       _productRepository.SaveOrUpdate(item);
    }

    public void MethodForContent(IItem item)
    {
       _contentRepository.SaveOrUpdate(item);
    }

}

// this is your repository extension class.
public static class RepositoryExtension
{

   public static void SaveOrUpdate(this IRepository repository, T item) where T : IItem
   {
      repository.SaveOrUpdate(item);
   }

}

// you can also use a base class.
interface IItem
{
   ...
}

class Product : IItem
{
  ...
}

class Content : IItem
{
  ...
}
Run Code Online (Sandbox Code Playgroud)