Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement multiple times the same generic interface that includes properties with different type parameters

Well from the beginning, I've got a simple generic interface:

public interface IItemContainer<T> where T : Item
{
    T ChosenItem { get; set; }
}

And an class that implements it multiple times:

public class ChosenItemsContainer : IItemContainer<FabulousItem>, IItemContainer<NiceItem>, IItemContainer<GreedyItem>
{

    public FabulousItem ChosenItem { get; set; }
    NiceItem IItemContainer<NiceItem>.ChosenItem { get; set; }
    GreedyItem IItemContainer<GreedyItem>.ChosenItem { get; set; }
}

I can't make the ChosenItems of types NiceItem and GreedyItem public, and also I can't access it like this:

ChosenItem<GreedyItem> = new GreedyItem();

cuz' I've got an error:

'GreedyItem' is a type, which is not valid in the current context

Is there anyway to use those props in this manner or I've got it all wrong and should do It with Dictionary or other way?

like image 270
Kamil Stadryniak Avatar asked Oct 15 '25 16:10

Kamil Stadryniak


1 Answers

When you like to keep your generic IItemContainer you can implement a GetChosenItem and SetChosenItem method like this.

public class ChosenItemsContainer : IItemContainer<FabulousItem>, IItemContainer<NiceItem>, IItemContainer<GreedyItem>
{
    FabulousItem IItemContainer<FabulousItem>.ChosenItem { get; set; }
    NiceItem IItemContainer<NiceItem>.ChosenItem { get; set; }
    GreedyItem IItemContainer<GreedyItem>.ChosenItem { get; set; }

    public T GetChosenItem<T>()
        where T : Item
    {
        return ((IItemContainer<T>)this).ChosenItem;
    }

    public void SetChosenItem<T>(T value)
        where T : Item
    {
        ((IItemContainer<T>)this).ChosenItem = value;
    }
}

Which comes very close to what you were trying to do.

container.SetChosenItem<NiceItem>(new NiceItem());
like image 179
Pidon Avatar answered Oct 18 '25 06:10

Pidon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!