【发布时间】:2017-07-07 15:46:40
【问题描述】:
我有两个接口:
public interface IDbModel {}
public interface IDmModel {}
以及由此派生的类:
public class DbModel : IDbModel {}
public class DmModel : IDmModel {}
public class Middle { }
我还有两个有限制的接口:
public interface IRule { }
public interface IRule<in TInput, out TOutput> : IRule
where TInput : IDmModel
where TOutput : IDbModel
{
TOutput Apply(TInput elem);
}
还有一个从这个接口派生的抽象类:
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) { ... }
}
在此之后,我创建了从这个抽象类派生的两个类:
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 : IRule : IRule
当我尝试将 RuleB 的对象转换为 IRule<IDmModel, IDbModel> 时发生未处理的异常
无法将“ParsreCombinators.RuleB”类型的对象转换为“ParsreCombinators.IRule`2[ParsreCombinators.IDmModel,ParsreCombinators.IDbModel]”类型。
var ruleB = (IRule<IDmModel, IDbModel>)new RuleB(); // Exception
IDbModel dbModel = ruleB.Apply(new DmModel());
this 有什么问题
为了使示例不那么混乱,我对其进行了简化:
编辑:
在我理解的答案之后,问题是什么,为了使示例不那么混乱,我将其简化:
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(); // Exception
【问题讨论】:
标签: c# generics inheritance multiple-inheritance