Foreach - various instructions depending on the type of elements in the <FooBar> list

I have an interface class FooBarand two specific classes, Fooand Bar.

If I'm foreachin FooBar, how can I use a different set of commands depending on whether my item is Fooor Bar? (for example, since Foothey Bardo not have the same properties).

+4
source share
1 answer

Three options.

, Foo Bar FooBarBase - , FooBar - , DoStuff(). Foo Bar DoStuff().

, .

public interface FooBar {
    void DoStuff(SomeFrameworkThing x);
}

...

List<FooBar> myFooAndBarList = new myFooAndBarList() { ... };

var thing = new SomeFrameworkThing(/* long list of murky parameters, all different */);

foreach (var fb in myFooAndBarList) {
    fb.DoStuff(thing);
}

, , , (, ), . , , . # 7 , (1).

foreach (var o in myFooAndBarList) {
    if (o is Foo) {
        var f = o as Foo;
        f.FooMethod();
        f.FooProperty = "lol";
    }
    else if (o is Bar) {
        var b = o as Bar;
        b.BarMethod(234, 345);
        b.BarProp = new Dictionary<Foo, List<Bar>>();
    }
}

, , , , , dynamic:

public void DoStuff(Foo f) {
    //  stuff
}

public void DoStuff(Bar b) {
    //  other stuff
}

...

foreach (dynamic d in myFoAndBarList) {
    DoStuff(d);
}

. . ; , , , , .

(1) , Visual Studio . "NO SYNTAX FOR YOU".

+5

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


All Articles