我很好奇为什么这是编译错误:
public abstract class AbstractThingList<T> : List<T>
{
protected QueryBuilder<TH> Query<TH>(string query) where TH : AbstractThingList<T>
{
// Argument 1: cannot convert from 'AbstractThingList<T>' to 'TH'
return new QueryBuilder<TH>(this, query);
}
protected class QueryBuilder<TH> where TH : AbstractThingList<T>
{
private readonly TH Container;
public QueryBuilder(TH container, string query)
{
Container = container;
}
public TH Execute()
{
return Container;
}
}
}
我收到错误消息Argument 1: cannot convert from 'AbstractThingList<T>' to 'TH'
,但是QueryBuilder将TH
约束为AbstractThingList<T>
(与外部类完全相同的T
),其中“ this”绝对是的一个实例。
我错过了什么吗?
答案 0 :(得分:1)
在html {
scroll-behavior: smooth;
}
方法中,虽然Query
被约束为TH
的子类型,但是AbstractThingList<T>
的类型是this
,并且不一定AbstractThingList<T>
的子类型。一个简单的反例是:
TH
由于public class ThingList1 : AbstractThingList<string> { }
public class ThingList2 : AbstractThingList<string> {
private void SomeMethod() {
this.Query<ThingList1>("query")
}
}
不是ThingList2
的子类型,因此正确禁止这样做。