2017-08-23 9 views
0

として使用したとき、私はその後、私は次のような方法インタフェースcontravariance型制約

public class RuleEngine<TContext> 
{ 
    public void Register<TRule, TSource, TResult>() // I would like to keep it just Register<TRule> but compiler would not let me 
     where TRule : ITransformationRule<TSource, TResult, TContext> {...} 
} 

を持つルールエンジンを持っているそして今、私がしたいことから

public interface ITransformationRule<in TSource, in TResult, in TContext> {...} 
public class MyRule : ITransformationRule<object, object, object> {...} 

インタフェースおよび派生型を持っていますそのルールをどこかで登録してください:

var engine = new RuleEngine<object>(); 
engine.Register<MyRule>(); // this fails to compile 
engine.Register<MyRule, object, object>(); // this is OK 

私はどのようにして1つのタイプのパーameter(MyRule)とTSourceとTResultを指定する必要はありませんか?私はそれから制約を落とすことができますが、私はそれを保つつもりです。

+1

何がしなければ 'ます。public void登録​​()ここで、TRule:ITransformationRule <オブジェクト、オブジェクト、TContext> '? –

+0

私はこのアプローチを試しましたが、うまくいきませんでした – Tamagochi

答えて

0

これを試してみてください:

public interface ITransformationRule<in TSource, in TResult, in TContext> {} 
public class MyRule : ITransformationRule<object, object, object> {} 

public class RuleEngine<TContext, TSource, TResult> 
{ 
    public void Register<TRule>() // I would like to keep it just Register<TRule> but compiler would not let me 
     where TRule : ITransformationRule<TSource, TResult, TContext> 
    { 

    } 

} 

var engine = new RuleEngine<object, object, object>(); 
engine.Register<MyRule>(); 

EDIT:ヤクブDąbekのアプローチを使用して

public interface ITransformationRule<in TSource, in TResult, in TContext> { } 
public class MyRule : ITransformationRule<object, object, object> { } 

public class RuleEngine<TContext> 
{ 
    public void Register<TRule>() // I would like to keep it just Register<TRule> but compiler would not let me 
     where TRule : ITransformationRule<object, object, TContext> 
    { 

    } 

} 

var engine = new RuleEngine<object>(); 
engine.Register<MyRule>(); 
+0

私のソリューションの設計を見直して、私の場合はこれが最良の選択肢になると決めました。ありがとうございました。 元の方法で(RuleEngineに型修飾子を追加しなくても)それを実行できるのであれば、まだ興味があります。 – Tamagochi

+0

JakubDąbekアプローチはもう一つの選択肢です。私はそれを使って私の例を更新します。 –

+0

しかし私はより制限的だと思います。あなたのユースケースに依存して、解決策であるか否か。 –

関連する問題