说我有以下
public interface IInterval<T>
{
T Start { get; }
T Stop { get; }
}
public class DateTimeInterval : IInterval<DateTime>
{
private DateTime _start;
private DateTime _stop;
public DateTimeInterval(DateTime start, DateTime stop)
{
_start = start; _stop = stop;
}
public DateTime Start
{
get { return _start; }
}
public DateTime Stop
{
get { return _stop; }
}
}
public class SortedIntervalList<T>
where T : IInterval<T>, IComparable<T>
{
}
如果我现在尝试实例化容器
var test = new SortedIntervalList<DateTimeInterval>();
我收到编译错误
类型&#39;测试&#39;不能用作类型参数&#39; T&#39;在通用 类型或方法
TestContainer<T>
。没有隐含的参考 转换为&#39;测试&#39;到ITest<Test>
。
为什么会这样?
关于修改记录的注意事项
为清楚起见,原始问题的类别包括在下面
public interface ITest<T>
{
int TestMethod();
}
public class Test : ITest<bool>
{
public int TestMethod()
{
throw new NotImplementedException();
}
}
public class TestContainer<T>
where T : ITest<T>
{
}
答案 0 :(得分:4)
where T : ITest<T>
您的班级继承ITest<bool>
,ITest<T>
(T
)不是Test
。
由于错误试图告诉您,这不符合您的通用约束,因此您无法做到。
答案 1 :(得分:2)
因为您希望T
中的TestContainer<T>
为ITest<T>
。这没有意义。我想你的意思是:
public class TestContainer<C, T>
where C : ITest<T>
{
}
您问题中的更新代码:
public class SortedIntervalList<C, T>
where C : IInterval<T>, IComparable<T>
{ }
使用:
test = new SortedIntervalList<DateTimeInterval, DateTime>();