[英]Cannot convert type to constrained generic of exact same type
I'm curious as to why this is a compilation error:我很好奇为什么这是一个编译错误:
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;
}
}
}
I receive the error message Argument 1: cannot convert from 'AbstractThingList<T>' to 'TH'
, however QueryBuilder constrains TH
to AbstractThingList<T>
(the exact same T
as used in the outer class), of which "this" is most definitely an instance of.我收到错误消息
Argument 1: cannot convert from 'AbstractThingList<T>' to 'TH'
,但是 QueryBuilder 将TH
限制为AbstractThingList<T>
(与外部类中使用的T
完全相同),其中“this”是绝对是一个实例。
Have I missed something?我错过了什么吗?
Within the Query
method, while TH
is constrained to be a subtype of AbstractThingList<T>
, the type of this
is AbstractThingList<T>
and it is not necessarily a subtype of TH
.在
Query
方法中,虽然TH
被限制为AbstractThingList<T>
的子类型, this
的类型是AbstractThingList<T>
并且它不一定是TH
的子类型。 A simple counterexample would be:一个简单的反例是:
public class ThingList1 : AbstractThingList<string> { }
public class ThingList2 : AbstractThingList<string> {
private void SomeMethod() {
this.Query<ThingList1>("query")
}
}
this is correctly disallowed since ThingList2
is not a subtype of ThingList1
.这是正确不允许的,因为
ThingList2
不是ThingList1
的子类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.