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

时间:2019-11-13 23:28:22

标签: c# generics

我很好奇为什么这是编译错误:

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”绝对是的一个实例。

我错过了什么吗?

1 个答案:

答案 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的子类型,因此正确禁止这样做。