C# 減少if嵌套


最近維護一批代碼,其中包括一堆if...的使用,多的情況嵌套8、9層,痛苦不堪,所以搜尋一些可以降低if...else的方法來改善一下代碼,寫個簡單總結。

 

 

 第一種:

優化前 

if (measuredValue > 8)
    return 5 * measuredValue * measuredValue - 3;
            
if (measuredValue > 4)
    return 4 * measuredValue - 2;

if (measuredValue >= 0)
    return 3 * measuredValue - 1;

return 2 * measuredValue;

使用列表和linq優化后(摘自:https://www.linkedin.com/pulse/if-less-programming-c-jiri-pokorny

using System;
using System.Linq;

namespace ConsoleApp1
{
    internal class Program
    {
        private static readonly MeasureTransform[] Transformations =
           new MeasureTransform[]
           {
            // 這個順序決定了判斷先后順序
            new MeasureTransform(m => m > 8, m => 5 * m * m - 3),
            new MeasureTransform(m => m > 4, m => 4 * m - 2),
            new MeasureTransform(m => m >= 0, m => 3 * m - 1),
            new MeasureTransform(m => true, m => 2 * m)
           };

        private static void Main(string[] args)
        {
            var executor = Transformations.First(t => t.CanApply(16));
            Console.Write(executor.Transform(16));
        }
    }

    internal class MeasureTransform
    {
        public MeasureTransform(Func<int, bool> canApply, Func<int, int> transform)
        {
            CanApply = canApply ?? throw new ArgumentNullException(nameof(canApply));
            Transform = transform ?? throw new ArgumentNullException(nameof(transform));
        }
        public Func<int, bool> CanApply { get; set; }
        public Func<int, int> Transform { get; set; }
    }
}

第二種:使用邏輯運算符改善

using System;
using System.Linq;

namespace ConsoleApp1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            int a = 10;
            int b = 10;

            // 優化前
            if (a > 5)
            {
                if (b > 10)
                {
                    Console.Write("");
                }
            }

            // 優化后
            if (a > 5 && b > 10)
            {
                Console.Write("");
            }
        }
    }
}

第三種:從業務邏輯角度看看有沒有多余的判斷

using System;
using System.Linq;

namespace ConsoleApp1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            System.UInt32 a = 10;
            int b = (int)a + 10;

            // 優化前
            if (a > 10)
            {
                if (b > 10)
                {
                    Console.Write("");
                }
            }

            // 優化后
            if (a > 10)
            {
                Console.Write("");
            }
        }
    }
}

第四種:使用三元運算符

優化前

namespace ConsoleApp1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            System.UInt32 a = 10;
            uint c;
            if (a > 10)
            {
                c = a;
            }
            else
            {
                c = a + 10;
            }
        }
    }
}
View Code

優化后

using System;
using System.Linq;

namespace ConsoleApp1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            System.UInt32 a = 10;
            int b = (int)a + 10;

            // 優化前
            var c = a > 10 ? a : a + 10;

        }
    }
}
View Code

第五種:太多if..else if...效率低,使用switch...case...,也好看點。

第六種:從架構層面使用依賴注入,反射之類的,參考https://www.c-sharpcorner.com/forums/how-can-i-remove-multiple-if-statement

第七種:使用goto(注意:goto塊是會按順序執行的 例如:有label1、label2、label3 塊按順序寫,如果label1執行完沒有goto label3,則label2也會執行)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM