首页 > 解决方案 > Is it possible to re-write this class without using "this is"

问题描述

I reviewed this code and I want to refactor keeping the same logic without using this is

class Animal
{
    public void Verify()
    {
        if (this is Animal) {
            Console.WriteLine("Animal");
        } else if (this is Person) {
            Console.WriteLine("Person");
        } else if (this is Home) {
            Console.WriteLine("Home");
        } else {
            Console.WriteLine("*******");
        }
    }
}
class Person
...
class Home
...

标签: c#asp.net.netc#-6.0

解决方案


它可能算得太相似了,但是switch (this)使用“模式匹配” iecase Person:可能是一种选择,但是 IMO 在这里更好的方法是多态性,因此:在基类中有一个virtualor方法,并且它适用于每个子类。现在多态性为您处理选择。abstractoverride


推荐阅读