Cannot convert from Foo<F> to F?

本文关键字:to gt lt convert from Foo Cannot | 更新日期: 2023-09-27 18:05:52

我在c#中使用 crtp风格的泛型结构,并有这些类:

public abstract class Foo<F> where F : Foo<F>
{ 
    public abstract Bar<F> Bar { get; }
    public void Baz()
    {
        return this.Bar.Qux(this); //Error is here: "Argument 1: Cannot convert from 'Foo<F>' to 'F'
    }
}
public abstract class Bar<F> where F : Foo<F>
{
    public abstract void Qux(F foo);
}

这对我来说似乎很奇怪,考虑到this应该总是一个Foo,对吗?

Cannot convert from Foo<F> to F?

在此上下文中,thisFoo<F>。将Qux的论证声明为F。需要更改为Foo<F>:

  public abstract class Foo<F> where F : Foo<F> {
    public abstract Bar<F> Bar { get; }
    public void Baz() {
      Bar.Qux(this);
    }
  }
  public abstract class Bar<F> where F : Foo<F> {
    public abstract void Qux(Foo<F> foo);
  }