重构方法 (C#)



>我有方法:

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

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

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

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

如果使用的是 C# 7 或更高版本,还可以将该方法编写为表达式体:

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

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

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

private static PlantMoveType[] _plantStates = 
new []{PlantMoveType.PlantReady, PlantMoveType.PlantRelase};
private bool MyMethod(PlantMoveType plantMoveType)
{
return _plantStates.Contains(plantMoveType);
}

最新更新