c# - 我可以将派生类中的这些方法与基类中的方法组合替换吗?

标签 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;
        }
    }

加上更多仅在传递给它们的类上有所不同的方法。

是否有某种方法可以在基类中对这些方法进行编码,而不是在每个派生类中重复该方法?我正在考虑基于泛型的东西,但我不确定如何实现,也不知道如何传递 _productRepository。

仅供引用,这是 _productRepository 和 _contentRepository 的定义方式:

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

最佳答案

是的,你可以。

简单的方法是使用接口(interface)和继承。紧耦合

另一种方法是依赖注入(inject)。失去耦合,更好。

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

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
{
  ...
}

关于c# - 我可以将派生类中的这些方法与基类中的方法组合替换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8557996/

相关文章:

c# - 如何在 DataGridView 显示对象的值中自定义控件?

c# - 如何在 Visual C# 中清除数组

c# - 抛出异常应该是第一件事吗?

c# - 从内存流添加附件

c# - 在 Windows 上使用 Mono Runtime 而不是 Microsoft 的 Monodevelop

c# - 使用 WCF 将数据推送到客户端的服务器推送技术

c# - 如何在 C# java 或任何语言中创建这样的工具/GUI 生成器

c# - Roslyn 的 ".WithFooToken()"调用是否多余?

c# - 将数据作为原始数据传递给打印机

c# - 不可变的集合?