【问题标题】:Is it possible to re-write this class without using "this is"是否可以在不使用“this is”的情况下重写此类
【发布时间】:2021-08-02 04:49:29
【问题描述】:

我查看了这段代码,我想在不使用 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
...

【问题讨论】:

  • (GetType() == typeof(Animal)
  • 这将始终打印“Animal”。
  • 这看起来像是一个接口的工作,而不是else ifs的序列。
  • 这里应该有继承层次吗?我看不出this is Animal 怎么会是假的。

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


【解决方案1】:

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

【讨论】:

  • 对不起,你能写个例子吗?
【解决方案2】:

如果你不介意一点反思:

    Console.WriteLine(this.GetType().Name);

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 2016-03-11
    • 1970-01-01
    • 2011-10-26
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2011-03-18
    相关资源
    最近更新 更多