vendredi 20 septembre 2019

Cannot implicitly convert type implementation to interface

all. Having difficulties in structuring application and applying design patterns. Initially was thinking about strategy pattern.

  • I want a common interface for setting and getting Item and Items details;
  • Interface implementations suits different contexts (e.g. furniture, toy) but all have same actions use the implementation
  • according to the context used all items derive from legacy BaseItem that has no properties on it

What I need:

/*client code*/
IItemHolder<BaseItem, BaseItem> itemHolder = null; // want to make it generic, abstract
switch (context)
{
    case "BigItems":
        // Exception "Cannot implicitly convert 'type' implementation to 'interface'
        itemHolder = new BigItemHolder(); 
        break;
    case "SmallItems":
        //itemHolder = new SmallItemHolder();
        break;
}

string itemTypeId = Session.GetSelectedItem(itemHolder.ItemTypeIdConstant);
string itemId = itemHolder.GetItemId(item);
string itemProperty = itemHolder.GetItemProperty(item);

/* structure I have */
class BaseItem { }
class BigItem : BaseItem { }

/* structure I am trying to implement */
interface IItemHolder<TBase> where TBase : BaseItem
{
    string ItemTypeIdConstant { get; }
    string GetItemId(TBase item);
    string GetItemProperty(TBase item);
    TBase GetItem(string itemId);
}

class BigItemHolder : IItemHolder<BigItem>
{
    public string ItemTypeIdConstant => throw new NotImplementedException();

    public BigItem GetItem(string itemId) { /**/ }

    public string GetItemId(BigItem item) { /**/ }

    public string GetItemProperty(BigItem item) { /**/ }
}

Covariance and contravariance in the interface does not help me much as same parameter can be input and output, unless splitting one generic type into two generic types

Aucun commentaire:

Enregistrer un commentaire