【问题标题】:Refactor method (C#) [duplicate]重构方法(C#)[重复]
【发布时间】:2019-09-18 06:16:19
【问题描述】:

我有方法:

private bool MyMethod(PlantType plantType)
{
    return plantType.PlantMoveType == PlantMoveType.PlantReady 
           || plantType.PlantMoveType == PlantMoveType.PlantRelase
}

我可以把它写成其他方式吗?也许使用 LINQ?

【问题讨论】:

  • 目前的方式有什么问题?你想缩短它还是什么?
  • 你还有什么意思?我唯一能想到的另一件事是private bool MyMethod(PlantType plantType) => new [] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase}.Contains(plantType.PlantMoveType);
  • 例如 LINQ 现在很流行我想知道我在这里如何使用它

标签: c# linq methods refactoring


【解决方案1】:

一种方法是将要检查的枚举值放入一个数组中,然后调用Contains

return new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
                 .Contains(plantType.PlantMoveType);

如果你使用的是C# 7或更高版本,你也可以将方法写成expression-bodied

private bool MyMethod(PlantType plantType) =>
    new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
        .Contains(plantType.PlantMoveType);

【讨论】:

  • 谢谢@Sweeper 的快速回答,我会尽量使用你的第一个提示
【解决方案2】:

一个小的简化是传递属性PlantMoveType 的类型(枚举?)而不是PlantType 作为参数。

除此之外,您可以声明要检查的类型,例如数组。如果您想重用该数组,也可以在方法范围之外声明它:

private static PlantMoveType[] _plantStates = 
   new []{PlantMoveType.PlantReady, PlantMoveType.PlantRelase};

private bool MyMethod(PlantMoveType plantMoveType)
{
    return _plantStates.Contains(plantMoveType);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多