public interface IShape{}
public class Rectangle : IShape{}
public class Base{}
public class Derived : Base{}
public interface IFoo<out T, in U>
where T : IShape
where U : Base
{
T Convert(U myType);
}
public class MyFoo : IFoo<Rectangle, Derived>
{
public Rectangle Convert(Derived myType)
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
IFoo<IShape, Base> hmm = new MyFoo();
}
}
上記のコードを考えると、コンパイラは型MyFoo
をに割り当てる方法を判断できません。これはIFoo<IShape, Base>
おそらく、U
より少ない派生を受け入れることができることを意味する out として設定されているためです。ただし、Derived
は、まあ、 よりも派生しBase
ているため、コンパイラ エラーが発生します。
この例は不自然ですが、扱っている実装はMyFoo
ファクトリから返されるものです。
はU
パラメーターとして使用されますが、ジェネリック インターフェイスに割り当てようとしたときの出力でもありますが、out
ここではキーワードを使用できません。どうすればこれを回避できますか?