Cannot convert from Foo<F> to F?

别等时光非礼了梦想. 提交于 2020-01-05 22:46:12

问题


I'm using a CRTP-style generic construct in C#, and have these classes:

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 seems very strange to me, considering this should always be a Foo, right?


回答1:


In that context, this is a Foo<F>. The argument of Qux is declared as F. It needs to be changed to 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);

  }


来源:https://stackoverflow.com/questions/31771282/cannot-convert-from-foof-to-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!