7

これが私が扱っているジェネリッククラスです:

 public interface IRepository<T> where T : EntityObject
{
    RepositoryInstructionResult Add(T item);
    RepositoryInstructionResult Update(T item);
    RepositoryInstructionResult Delete(T item);
}
public class Repository<T> : IRepository<T> where T : EntityObject
{

    RepositoryInstructionResult Add(T item)
    { //implementation}
    RepositoryInstructionResult Update(T item);
    { //implementation}
    RepositoryInstructionResult Delete(T item);
    { //implementation}
 }

今、私はt:特定のタイプのときのメソッドの振る舞いを時々変更しようとしています。次のようなことは可能ですか?この特定の試みはエラーを出します(エラー5:「リポジトリ」の部分的な宣言は同じタイプのパラメータ名を同じ順序で持つ必要があります)。

public class Repository<Bar> //where Bar : EntityObject
{
    RepositoryInstructionResult Add(Bar item)
    { //different implementation to Repository<T>.Add() }
    //other methods inherit from Repository<T>
 }
4

4 に答える 4

8
public class BarRepository : Repository<Bar>
{ 
    RepositoryInstructionResult Add(Bar item) 
    { //different implementation to Repository<T>.Add() } 
    //other methods inherit from Repository<T> 
} 
于 2012-06-14T13:42:25.067 に答える
2

リポジトリクラスにRepositoryBaseという名前を付け、インターフェイスメソッドを仮想化します。それらをRepositoryBaseクラス内に一般的な方法で実装しますが、uがメソッドを仮想としてマークしたため、派生クラスの機能をオーバーライドできるため、コードは次のようになります。

 public interface IRepository<T> where T : EntityObject
 {
    RepositoryInstructionResult Add(T item);
    RepositoryInstructionResult Update(T item);
    RepositoryInstructionResult Delete(T item);
 }

 public class Repository<T> : IRepository<T> where T : EntityObject
 {
    virtual RepositoryInstructionResult Add(T item)
    { //implementation}
    virtual RepositoryInstructionResult Update(T item);
    { //implementation}
    virtual RepositoryInstructionResult Delete(T item);
    { //implementation}
  }

バーオブジェクトの更新メソッドに対してカスタムロジックを実行する必要がある場合は、派生クラスに名前を付けてBarRepositoryに名前を付け、Repositorybaseクラスの更新メソッドをオーバーライドします。ここで、ベース実装を呼び出すか、独自のロジックで処理することができます。

 public class BarRepository : Repositorybase<Bar>
 {
    public override RepositoryInstructionResult Update(Bar item);
    {
       //Call base method if needed
       //Base.Update(item);

       //implement your custom logic here
    }
  }
于 2012-06-14T14:07:01.933 に答える
0

あなたの質問への直接の答えとして:あなたが示したものに最も近い可能性のあることはT、実行時にの実際の値をチェックすることです。addメソッドでは、次のように記述できます。

if (typeof(T) == typeof(Bar)) {
    // your Bar-specific code
}
// ...

これは、特に、異なる方法で処理したい特殊なタイプが1つまたは2つ以上ある場合は、パフォーマンスの点であまり良くない可能性があることに注意してください。

それ以外の唯一の解決策は、他の回答で概説されているように、基本クラスの実際の型引数を指定するサブクラスです。

于 2012-06-14T14:17:57.083 に答える
0

拡張メソッドを使用します:

public static void DoSomething(this repository<Bar> repo)
{
  //your custom code goes here
}
于 2016-06-19T11:24:08.197 に答える