用作类型约束时的接口逆转

时间:2017-08-23 13:00:48

标签: c#

我有一个接口和一个派生类型

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

然后我有一个规则引擎,它有以下方法

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

现在我想在某处注册该规则:

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

问题是如何只使用一个类型参数(MyRule)调用Register方法,而不必指定TSource和TResult?我知道我可以放弃约束,但我打算保留它。

1 个答案:

答案 0 :(得分: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>();

编辑:使用JakubDą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>();