子のオブジェクトを画面にレンダリングするライブラリを作成しています。子オブジェクトは抽象クラスであり、このライブラリのユーザーがこの抽象クラスから独自の子を派生させることを意図しています。汎用インターフェイスへのC#型キャスト
public abstract class Child : IRenderable {}
public interface IParent<T> where T : Child
{
IEnumerable<T> Children { get; }
}
合併症ではなく、私がIRenderablesの束を持って、私はで動作するようにIParentのリストを持っていないということです。図書館の利用者は、このような何かを書くことが予想されます。
引き分けにpublic class Car : IRenderable { }
public class Cow : IRenderable, IParent<Calf> { }
public class Calf : Child { }
// note this is just an example to get the idea
public static class App
{
public static void main()
{
MyLibraryNameSpace.App app = new MyLibraryNameSpace.App();
app.AddRenderable(new Car()); // app holds a list of IRenderables
app.AddRenderable(new Cow());
app.Draw(); // app draws the IRenderables
}
}
()、ライブラリべきキャストとはIRenderableもIParentであるかどうかを確認してください。しかし、私は子牛について知らないので、私は牛を投げるべきか分からない。
// In Draw()
foreach(var renderable in Renderables)
{
if((parent = renderable as IParent<???>) != null) // what to do?
{
foreach(var child in parent.Children)
{
// do something to child here.
}
}
}
どうすればこの問題を解決できますか?これは共分散ジェネリックスと何か、それとも何か(私は共分散概念に精通していません)ですか?
'IParent
@MarcGravell:ありがとう、修正されました。制約を見過ごした。 – Heinzi
編集内容に余分な説明があります。本当に助けになりました。ありがとう。 – Jake