我有一套由此界面定义的规则:
public interface IRule<in T>
{
bool IsBroken(T dataObject);
}
示例实施:
class Rule1:IRule<DateTime>
{
public bool IsBroken(DateTime dataObject)
{
throw new NotImplementedException();
}
}
class Rule2:IRule<int>
{
public bool IsBroken(int dataObject)
{
throw new NotImplementedException();
}
}
我还有另一个课程,如下所示:
class RulesCollection
{
public IEnumerable<IRule<what>> GetAllRules()
{
yield return new Rule1();
yield return new Rule2();
}
}
这里面临的问题是 - 如何将规则1&amp; rule2 into IEnumerable<IRule<T>>
,因为对于各种规则来说T会有所不同,因为它允许我这样做。有没有办法解决这个问题?
使用.NET 4.
答案 0 :(得分:0)
根据IsBroken
的返回值的含义,您可以执行以下操作:
public class RuleWrapper<T> : IRule<object>
{
private readonly IRule<T> inner;
public RuleWrapper(IRule<T> inner)
{
this.inner = inner;
}
public bool IsBroken(object obj)
{
return obj is T && this.inner.IsBroken((T)obj);
}
}
然后:
public IEnumerable<IRule<object>> GetAllRules()
{
yield return new RuleWrapper<DateTime>(new Rule1());
yield return new RuleWrapper<int>(new Rule2());
}