C#:避免if(x为Foo){...} else if(x为Bar){...}为数据结构 [英] C#: Avoiding if (x is Foo) {...} else if (x is Bar) {...} for data structures

查看:140
本文介绍了C#:避免if(x为Foo){...} else if(x为Bar){...}为数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据结构系列,如:

I have a family of data structures like:

abstract class Base {...}
class Foo : Base {...}
class Bar : Base {...}

一个方法,它接受一个Base,并根据它的子类进行转换:

and a method which takes a Base and converts it depending on which subclass it is:

void Convert(Base b) {
  if (b is Foo) 
    // Do the Foo conversion
  else if (b is Bar) 
    // Do the Bar conversion
...

显然这是可怕的对象方向 - 转换方法必须知道Base的每个派生类,并且必须每次更改该基地扩展。解决这个问题的'正常'OO方法是使Base的每个派生类负责转换自身,例如

Obviously this is terrible object orientation - the Convert method has to know about every derived class of Base and has to be changed every time that Base is extended. The 'normal' OO way of solving this problem is to make each derived class of Base responsible for converting itself, e.g.

abstract class Base {
  abstract Converted Convert();
...}
class Foo : Base {
  override Converted Convert(){...}
...}
class Bar : Base {
  override Converted Convert(){...}
...}

然而在我编写的代码中Base是纯数据结构(只有getter和setter - 没有逻辑),而在另一个程序集中,我没有权限更改。有没有办法更好地构建不强制派生类的代码具有逻辑的代码?

However, in the code that I am writing Base is a pure data structure (only getters and setters - no logic), and it is in another assembly which I do not have permission to change. Is there a way of better structuring the code that does not force the derived classes of Base to have logic?

谢谢

推荐答案

如果你这么做,那么不要这样做。根本的问题是:

If it hurts when you do that then don't do that. The fundamental problem is:


我有一个方法需要一个 Base

由于这是根本问题,请删除它。完全摆脱这种方法,因为它是可怕的。

Since that is the fundamental problem, remove it. Get rid of that method entirely because it is awful.

替换为:

void Convert(Foo foo) {
   // Do the Foo conversion
}
void Convert(Bar bar) {
   // Do the Bar conversion
}

现在没有办法说谎,说可以转换任何 Base 其实不能。

Now no method has to lie and say that it can convert any Base when in fact it cannot.

这篇关于C#:避免if(x为Foo){...} else if(x为Bar){...}为数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆