如何消除switch

使用多态来消除switch:Link.

 

With polymorphism, this:

foreach (var animal in zoo) {
    switch (typeof(animal)) {
        case "dog":
            echo animal.bark();
            break;

        case "cat":
            echo animal.meow();
            break;
    }
}

becomes this:

foreach (var animal in zoo) {
    echo animal.speak();
}
posted @ 2018-03-06 14:21  jpgtama  阅读(232)  评论(0编辑  收藏  举报