c# - 在循环中嵌套条件

标签 c#

给定以下代码,是否有更好的方法来构造它?

foreach(Thing item in SomeRandomList)
{
    bool firstCondition = CalculateBool(item, someValue);
    bool secondCondition = CalculateBool(item, someOtherValue);

    //General things are done...
    if(firstCondition || secondCondition)
    {
        //semi-specific things are done...
        if(firstCondition)
        {
            //specific things are done...
        } 
        else
        {
            //specific things are done...
        }
    }
}

此外,如果有更多条件,即 3:

foreach(Thing item in SomeRandomList)
{
    bool firstCondition = CalculateBool(item, someValue);
    bool secondCondition = CalculateBool(item, someOtherValue);
    //imagine as many more as you want.
    bool nthCondition = CalculateBool(item, lastOtherValue);

    //General things are done...
    if(firstCondition || secondCondition || nthCondition)
    {
        //semi-specific things are done...
        if(firstCondition)
        {
            //specific things are done...
        } 
        else if(secondCondition)
        {
            //specific things are done...
        }
        else
        { 
            //specific things are done...
        }
    }
}

最佳答案

是的:多态性。

从公共(public)基础派生Thing(或定义所有Thing 实现的接口(interface))

否则,将条件测试代码移动到 Thing 上的方法中。

关于c# - 在循环中嵌套条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2285704/

相关文章:

c# - 输入语言 Hook

c# - 伪造派生类但调用真正的构造函数并忽略基类构造函数

c# - 在 C# 中无限旋转列表中的 3 个项目的最佳方法是什么

c# - 如何修复 Automapper 将连接表映射到 ViewModel

c# - SerialPort UnauthorizedAccessException

c# - Wpf 绝对与相对包 URI

c# - 如何禁止因在 .NET 项目中使用 COM 引用而产生的编译器警告

c# - 通过在 DataContext 上使用 GetTable 方法检索一个对象

c# - 最小起订量在第二次验证时未执行任何调用

c# - LINQ to SQL 的内存泄漏