无法从Foo <f>转换为F?

时间:2015-08-02 11:12:04

标签: c# generics

我在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,对吧?

1 个答案:

答案 0 :(得分:0)

在这种情况下,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);

  }
相关问题