I have two interfaces:
public interface IDbModel {} public interface IDmModel {}
And the classes derived from this:
public class DbModel : IDbModel {} public class DmModel : IDmModel {} public class Middle { }
I also have two interfaces with restrictions:
public interface IRule { } public interface IRule<in TInput, out TOutput> : IRule where TInput : IDmModel where TOutput : IDbModel { TOutput Apply(TInput elem); }
And one abstract class derived from this interface:
public abstract class Rule<TDmModel, TMiddle, TDb> : IRule<TDmModel, TDb> where TDmModel : IDmModel where TDb : IDbModel { private readonly Func<TDmModel, TMiddle> _rule; protected Rule(Func<TDmModel, TMiddle> rule) { _rule = rule; } protected abstract TDb Apply(TMiddle transformedMessage); public TDb Apply(TDmModel elem) { ... } }
After that, I created two classes derived from this abstract class:
public class RuleA : Rule<DmModel, Middle, DbModel> { public RuleA(Func<DmModel, Middle> rule) : base(rule) {} protected override DbMode Apply(Middle transformedMessage) { ... } } public class RuleB : RuleA { public RuleB() : base((dm) => new Middle()) {} }
RuleB: RuleA: Rule <DmModel, Middle, DbModel>: IRule <IDmModel, IDbModel>: IRule
And when I try to pass an object RuleB in IRule<IDmModel, IDbModel> occours unhandled exception
Cannot pass an object of type "ParsreCombinators.RuleB" to enter "ParsreCombinators.IRule`2 [ParsreCombinators.IDmModel, ParsreCombinators.IDbModel]".
var ruleB = (IRule<IDmModel, IDbModel>)new RuleB();
What happened to this
To make the example less confusing, I simplify it:
EDIT:
After the answers, I realized what the problem is and to make the example less confusing, I simplify it:
public interface IDbModel {} public interface IDmModel {} public class DbModel : IDbModel {} public class DmModel : IDmModel {} public interface IRule<in TInput, out TOutput> where TInput : IDmModel where TOutput : IDbModel { TOutput Apply(TInput elem); } public class RuleA : IRule<DmModel, DbModel> { public DbModel Apply(DmModel elem) { ... } } var ruleA = (IRule<IDmModel, IDbModel>)new RuleA();