c# - 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
...
解决方案
它可能算得太相似了,但是switch (this)
使用“模式匹配” iecase Person:
可能是一种选择,但是 IMO 在这里更好的方法是多态性,因此:在基类中有一个virtual
or方法,并且它适用于每个子类。现在多态性为您处理选择。abstract
override
推荐阅读
- tfs - 在 Devops 中向团队 B 隐藏团队 A 的工作项
- c++ - 调试外部 CMake 项目(hunter_add_package)?
- java - 如何调用从 Java 代码返回 TABLE 类型的 postgresql 函数?
- python - 从一组文档中,如何在 python 中为 Mapreduce 计算单词、文档数和计数
- xml - 使用 Dart XML 自定义关闭标签 -
- c# - 如何摆脱此错误:并非所有代码路径都返回值
- css - 将选择样式应用于开槽元素?
- eclipse - 尝试从当前的过去 5 个工作日内在 android 应用程序中自动化 1 个测试场景(跳过周六、周日、固定假期)
- python-3.x - 使用 numpy 从数组创建矩阵
- google-cloud-platform - Gcloud 将图像推送到错误/旧项目