[英]Can I combine replace these methods in derived class with a method in the base class?
我有这样的方法:
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();
}
是的你可以。
最简单的方法是使用接口和继承。 紧密耦合
另一种方法是依赖注入。 失去耦合,更可取。
另一种方法是按如下方式使用泛型:
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
{
...
}
尝试使用通用方法在您的基类上花了很多时间并实现了它,您可以尝试以下链接: http : //msdn.microsoft.com/zh-cn/library/twcad0zb(v=vs.80).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.