C # .NET 4.0 and Generics

I was wondering if anyone can tell me if this behavior is possible in C # 4.0

I have a hierarchy of objects that I would like to keep strictly typed. Something like that

class ItemBase {}

class ItemType<T> where T : ItemBase 
{
   T Base { get; set; }
}


class EquipmentBase : ItemBase {}
class EquipmentType : ItemType<EquipmentBase> {}

What I want to do something like this

ItemType item = new EquipmentType();

And I want item.Base to return an ItemBase type. Basically, I want to know if it is smart enough to strongly typify a base class without strong typing. The advantage of this is that I can simply return ItemType back to EquipmentType and get all the strict typing back.

Maybe I'm thinking about it all wrong ...

+3
source share
3 answers

, :

ItemType<object> item = new EquipmentType();

# 4 :

  • , ,
  • ItemType T /, , T, T.

2 , , , , .

// this will not work
ItemType<object> item = new EquipmentType();
item.Base = new Object(); // this seems ok but clearly isn't allowed

+4

, ItemType ItemType<EquipmentBase> ItemType<Foo>. , .

ItemType<T>, ItemType undefined, .

ItemType<EquipmentBase> EquipmentType , ItemType<EquipmentBase>, ItemType<PersonType>.

0

I don't think the new C # 4.0 features will help you there. However, there is a way around this that has already been working since generalizations were introduced: you create an abstract base class with the same name as the general class, and put all the members that you want and which should not accept or return an argument of a generic type, for example:

class ItemBase {
}

abstract class ItemType {
    public ItemBase Base {
        get { return GetItemBase(); }
        set { SetItemBase(value); }
    }

    protected abstract void SetItemBase(ItemBase value);

    protected abstract ItemBase GetItemBase();
}

class ItemType<T> : ItemType where T : ItemBase {
    protected override sealed void SetItemBase(ItemBase value) {
        Base = (T) value;
    }

    protected override sealed ItemBase GetItemBase() {
        return Base;
    }

    public new T Base { get; set; }
}
0
source

Source: https://habr.com/ru/post/1740543/


All Articles