Common function in a derived class list

I feel that my question is pretty dumb, or another way of expressing this: I was too lost in my code to see a workaround. Stay with us too long and your vision will become narrower and narrower> <. Plus I'm not good enough with inheritance, polymorphism and so

Here is the idea: I have several lists of a derived class, and I would like to name the common functions in these lists (by entering and changing members of the base class). I feel that there is some relation to inheritance, but so far I have not managed to get it to work the way I want.

Here is a very simple example of what I intend to do:

class Baseclass
{
    public int ID;
    public string Name;
}
class DerivedClass1 : Baseclass
{
}

private void FuncOnBase(List<Baseclass> _collection)
{
    // ...

    foreach (Baseclass obj in _collection)
    {
        ++obj.ID;
    }

    // ...
}
private void FuncTest()
{
    List<DerivedClass1> collection1 = new List<DerivedClass1>();
    collection1.Add(new DerivedClass1() { ID = 1 });
    collection1.Add(new DerivedClass1() { ID = 2 });
    collection1.Add(new DerivedClass1() { ID = 3 });

    FuncOnBase(collection1);   //  ==> forbidden, cannot convert the derived class list to the base class list
}
+3
source share
2 answers

. A List<DerivedClass1> a List<Baseclass> - FuncOnBase Baseclass, .

:

private void FuncOnBase<T>(List<T> _collection) where T : Baseclass
{
    // ...

    foreach (T obj in _collection)
    {
        obj.ID++;
    }

    // ...
}

- , T ; , , T : new() () a params T[].

, IEnumerable<T> # 4.0/.NET 4.0, , IEnumerable<Baseclass> ( ), " ":

private void FuncOnBase(IEnumerable<Baseclass> _collection)
{
   ///...
}
+11

foreach, FuncOnBase(IEnumerable<Baseclass> collection), FuncTest :

FuncOnBase(collection1.Cast<Baseclass>());

List<T>, IEnumerable<T>, API, .

+2

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


All Articles