简体   繁体   English

无法将类型转换为完全相同类型的约束泛型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM