1. 程式人生 > 其它 >C#函數語言程式設計示例

C#函數語言程式設計示例

前一篇介紹了TypeScript函數語言程式設計示例,這次再寫一個C#的程式碼示例。 作為OOP語言,C#對FP的支援並沒有TS那麼好,不過也可以通過delegate,Func,Action,甚至是擴充套件方法(對delegate、Func等進行擴充套件)實現。

下面是程式碼示例,該示例假設有Product物件,其stock屬性為bool型別,根據其值決定對quantity屬性賦值,還是記錄log。普通的程式碼方式如下:

namespace FP
{
    class Product
    {
        public bool stock;
        public int quantity;
        public int count;
    }

    class Normal {
        public Normal() {
            var prod = new Product() { stock=true, quantity=100, count=10 };
            if(prod.stock) {
                prod.quantity *= 2;
            }
            else {
                Console.WriteLine("no stock");
            }
        }
    }
}

下面再來看採用delegate方式改造的結果

    delegate bool IfElse<P>(P p);
    delegate void True<T, U>(T t, U u);
    delegate void False<T>(T t);

    class FPDemo {
        static IfElse<Product> HasStock = (p) => p.stock;
        static True<Product, int> SetQuantity = (p, qty) => {
            p.quantity = qty;
        };

        static False<Product> LogError = (p) => {
            Console.WriteLine(p.quantity);
        };

        static Action<Product, IfElse<Product>, True<Product, int>, False<Product>> StockFunc = (prod, HasStock, SetQuantity, LogError) => {
            if(HasStock(prod))
            {
                SetQuantity(prod, prod.quantity*2);
            }
            else {
                LogError(prod);
            }
        };

        public FPDemo() {
            var prod = new Product() { stock=true, quantity=100, count=10 };
            StockFunc(prod, HasStock, SetQuantity, LogError);
        }
    }

這麼做的好處很明顯,把業務邏輯處理獨立出來,方便閱讀和複用。