开发者

How to use the derived type in a generic collection from an abstract class (C#)?

开发者 https://www.devze.com 2023-03-24 20:02 出处:网络
I have a generic collection that contains a method that the items in the collection need to call. Each item has a reference to the generic c开发者_开发知识库ollection. The problem is that I can\'t use

I have a generic collection that contains a method that the items in the collection need to call. Each item has a reference to the generic c开发者_开发知识库ollection. The problem is that I can't use the type of each item as the type passed to the generic collection.

The idea is like this (I know it doesn't compile):

    public class MyCollection<T>
    {
        public void Call(T item) { ... }
    }

    public abstract class MyItemBase
    {
        protected MyCollection<typeof(this)> _collection;
        public MyItem(MyCollection<typeof(this)> collection)
        {
            this._collection = collection;
        }

        public DoSomething()
        {
            this._collection.Call(this);
        }
    }

    public class MyItem : MyItemBase
    {
    }

Obviously, you can't declare MyCollection<typeof(this)> but I think by writing it this way you get the general idea of what I'm trying to do. Essentially, I want the abstract class' reference to the collection to mean MyCollection<MyClass>.

Is there any way to make this work?


First of all why is your ItemBase class containing an ItemCollection? Should it not be vice-versa, where your Collection class should contain Items?

However for your problem context, you can be type safe if you design your class this way :

 public class MyCollection<T> where T : MyItemBase<T>
{
    public void Call(MyItemBase<T> item) { }
}

public abstract class MyItemBase<T> where T : MyItemBase<T>
{
    protected MyCollection<T> _collection;

    protected MyItemBase(MyCollection<T> collection)
    {
        _collection = collection;
    }

    public void DoSomething()
    {
        _collection.Call(this);
    }
}

public class MyItem : MyItemBase<MyItem>
{
    public MyItem(MyCollection<MyItem> Collection)
        : base(Collection)
    {
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号