LINQ的恶搞……

本文展示了如何使用LINQ语法替代Lambda表达式实现相同的功能,并通过具体示例代码演示了这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在去年QCon SF的[url=http://www.infoq.com/interviews/LINQ-Erik-Meijer]一个访谈[/url]里,Erik Meijer提到可以把这样一个lambda表达式:
x => x + 1

写成:
from x in default(int)
select x + 1


原话是:
[quote="Erik Meijer"]In my talk on LINQ, I have an example of a really weird implementation that shows that you don't need lambda expressions. If you implement the sequence operator correctly you can say "from x in default(int) select x + 1" and that means "x => x + 1". You can do weird things like that, but again, I think we are very early in the development and when people will discover this, that LINQ is not just for collections, you will see many other applications of it.[/quote]

怪有趣(和无聊=w=)的。
实践一下,代码如下:
using System;

static class Int32Extensions {
public static Func<int, TR> Select<TR>(this int i, Func<int, TR> func) {
return func;
}
}

static class Program {
static void Main(string[] args) {
var f = from x in default(int)
select x + 1;
Console.WriteLine(f.GetType()); // System.Func`2[System.Int32,System.Int32]
Console.WriteLine(f(2)); // 3
}
}

连System.Linq都不需要引用,确实能行。呵呵,Erik真欢乐 XDD

话说这代码也能泛化到任意类型:
using System;

static class TExtensions {
public static Func<T, TR> Select<T, TR>(this T obj, Func<T, TR> func) {
return func;
}
}

static class Program {
static void Main(string[] args) {
var f = from s in default(string)
select s.Length;
Console.WriteLine(f.GetType()); // System.Func`2[System.String,System.Int32]
Console.WriteLine(f("oh my")); // 5
}
}

太邪恶了……(虽然函数不能像F#那样自动泛化比较不爽 =v=)
话说泛化到任意类型之后,编译会得到一个警告:
[quote]warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null[/quote]
不过实际上没关系,我们根本就没用过那个null。

======================================================

糟糕,刚才不小心点了提交,直接就发出来了……发的时候标题跟内容是脱节的 OTL
嘛,LINQ的语法是monadic syntax没错,不过跟这帖没关系 =v=
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值