2011-12-19 19 views
2

我有这样的方法:不同之处仅在传递给它们的类我可以将派生类中的这些方法与基类中的方法合并吗?

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(); 
    } 
+0

框架? – 2011-12-19 06:49:17

+0

不使用实体框架 – 2011-12-19 06:58:11

回答

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

你能给我一个我如何称通用的例子。 T和V的意义是什么? – 2011-12-19 06:57:28

+1

我已更新答案。 – DarthVader 2011-12-19 07:04:05

+0

这是一个很好的答案@DarthVader – 2011-12-19 07:05:50

相关问题