LINQ的恶搞……
程序员文章站
2022-06-04 14:05:16
...
在去年QCon SF的一个访谈里,Erik Meijer提到可以把这样一个lambda表达式:
写成:
原话是:
怪有趣(和无聊=w=)的。
实践一下,代码如下:
连System.Linq都不需要引用,确实能行。呵呵,Erik真欢乐 XDD
话说这代码也能泛化到任意类型:
太邪恶了……(虽然函数不能像F#那样自动泛化比较不爽 =v=)
话说泛化到任意类型之后,编译会得到一个警告:
不过实际上没关系,我们根本就没用过那个null。
======================================================
糟糕,刚才不小心点了提交,直接就发出来了……发的时候标题跟内容是脱节的 OTL
嘛,LINQ的语法是monadic syntax没错,不过跟这帖没关系 =v=
x => x + 1
写成:
from x in default(int) select x + 1
原话是:
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.
怪有趣(和无聊=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=)
话说泛化到任意类型之后,编译会得到一个警告:
引用
warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null
不过实际上没关系,我们根本就没用过那个null。
======================================================
糟糕,刚才不小心点了提交,直接就发出来了……发的时候标题跟内容是脱节的 OTL
嘛,LINQ的语法是monadic syntax没错,不过跟这帖没关系 =v=