我有这样的方法:
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/