避免在 C# 工厂方法中使用多个 if 语句

Avoiding multiple if statements in C# factory method

我有 C# application 将数据存储在 NoSQL database 中。该应用程序有一个存储库 class,它使用一系列对象将数据从 NoSQL 形式转换为 C# 模型使用的形式,反之亦然(本质上是一种 ORM 形式)。这些对象实现了一个 converter 接口,每个对象都在一个特定的 data type (string, bool, etc) 上工作。在内部,他们使用反射来执行转换。这些对象的实例是通过 returns 给定类型的对象的方法创建的。目前逻辑如下所示:

if(type == typeof(string)
    return new StringConverter(...);

if(type == typeof(int) || type == typeof(uint))
    return new IntegerConverter(...);

... // and so on

然而,所有这些 if 陈述都让我感到困扰。我知道我可以做一些事情,比如创建一个字典来将类型映射到创建方法,但我不确定这是否会产生更具可读性、易于 maintain/extend 的代码(?)。鉴于需要创建类型抽象,最好的方法是什么?欢迎任何建议。非常感谢。

理想情况下,嵌套 if-statements 是您要避免的。我引用的是微软的完整代码书。这个想法是,当您嵌套多达 3 层时,维护代码的开发人员或您作为开发人员的注意力会急剧减少。 在你的情况下,如果你的逻辑必须被硬编码,那么就没有办法绕过一系列 if 语句。然而,一个聪明的方法是遵循工厂设计模式。(四人帮)

您应该将 if 代码导出到工厂 class。

如你所见here,工厂是一个 GoF 模式,它生产 不同种类的物体。

在工厂里class,这个int case的数量是可以的。

你应该只避免嵌套的 if 语句,它们会使你的代码不可读

在可读性方面,你应该更喜欢

switch(type.FullName){
  case(typeof(int).FullName) => //your logic
  ...
}

switch-case-Statement 代码比 If-Else 更易读,而且速度更快。 HERE 您可以阅读更多相关信息:

For just a few items, the difference is small. If you have many items you should definitely use a switch.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.

正如其他人所说,将您的 switch-case 外包给工厂 Class。

我相信你将类型映射到字典的想法是你最好的选择,因为它实现了一个策略模式,并且本身就非常具有表现力。

var converterStrategies = new Dictionary<Object, IConverter>();
converterStrategies.Add(typeOf(string), new StringConverter(...));

然后在传入引用类型时使用 TryGetValue。

您可能会考虑将此字典作为 class 的私有成员,并在包含 class.

的初始化时填充它

Gary​​ McLean Hall 在他的 Adaptive Code via C# 一书中演示了这种模式,它在这种情况下对我帮助很大!