首页 > 解决方案 > 重构方法 (C#)

问题描述

我有方法:

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

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

标签: c#linqmethodsrefactoring

解决方案


一种方法是将要检查的枚举值放入数组中,然后调用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);

推荐阅读