2011-12-19 5 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を渡す方法もわかりません。そうすることができます

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

あなたはエンティティを使用していますフレームワーク? –

+0

エンティティフレームワークを使用していない –

答えて

5

はFYIここ_productRepositoryと_contentRepositoryが定義されている方法です。

簡単な方法は、インターフェイスと継承を使用することです。締め付け結合

別の方法は、依存性注入です。カップルを失い、好ましい。

さらに別の方法は、次のようにジェネリックを使用することです:

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の意義は何ですか? –

+1

私は答えを更新しました。 – DarthVader

+0

これは良い答えです@DarthVader –

関連する問題