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);
}
}
这么做的好处很明显,把业务逻辑处理独立出来,方便阅读和复用。
分类:
functional programming
, c#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具