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);
        }
    }

这么做的好处很明显,把业务逻辑处理独立出来,方便阅读和复用。

posted @ 2022-01-02 22:18  老胡Andy  阅读(204)  评论(0编辑  收藏  举报