当前位置: 移动技术网 > IT编程>开发语言>.net > 【C#进阶】拥抱Lambda(二)

【C#进阶】拥抱Lambda(二)

2019年04月02日  | 移动技术网IT编程  | 我要评论

李继耐简历,金榜大厦,网游之强者现世

  语言的设计,真的是挺有意思的。第一次看这个代码[1]时,旁人随口了一句“哇,好多实心句号”。

  当时马上一个想法是——怎么实现的?返回了对象,然后再调用方法?然后就放下了,后来发现,这个是真值得说一说的。

            var sim = new inputsimulator();
            sim.keyboard
               .modifiedkeystroke(virtualkeycode.lwin, virtualkeycode.vk_r)
               .sleep(1000)
               .textentry("notepad")
               .sleep(1000)
               .keypress(virtualkeycode.return)
               .sleep(1000)
               .textentry("these are your orders if you choose to accept them...")
               .textentry("this message will self destruct in 5 seconds.")
               .sleep(5000)
               .modifiedkeystroke(virtualkeycode.menu, virtualkeycode.space)
               .keypress(virtualkeycode.down)
               .keypress(virtualkeycode.return);

 

1. 神奇的链接(chaining

1.1 拓展方法

  想了很久该怎么引入话题,或者这样说,像这种写法,

  if (str == null || str == “”)

  相信刚刚开始编程的时候都这样写过,而c#语言规则里面,告诉我们可以这样写:

  string.isnullorempty(str);

  后来,有一天,我很自然地就写成这样了str.isnullorempty,当然,ide都没有弹出isnullorempty这个函数我就知道不对了。

 

  嗯,如果非要写成str.isnullorempty这样,大概会很麻烦。

  首先string类型就是seal,重写一个string类那就……

  可以写静态方法,但其实也不美观,因为还是要这样 isnullorempty_test(str), 那和string.isnullorempty(str);  是没有区别的。

  这个时候,故事终于来到——拓展方法(extension methods)。

 

  下个定义吧,好说话。

  拓展方法,就是把对象自己作为第一个传入参数的静态方法。(这个“对象自己”,需要在形参前加个 this 前缀)

没有规则总是会乱套的,拓展方法有些语法[2]:

l   必须在一个非嵌套的、非泛型的静态类中;

l   至少有一个参数(就是对象它自己);

l   第一个参数必须附加this关键字前缀;

l   第一个参数不能有其他任何修饰符(比如out或ref);

l   第一个参数的类型不能是指针类型。 

 

 

  那么string.isnullorempty(str);能怎么改?

    class program
    {
        static void main(string[] args)
        {
            string str = "";
            console.writeline(str.isnullorempty()); 
        }
    }

    static class nullutil
    {
        public static bool isnullorempty(this string text)
        {
            return string.isnullorempty(text);
        }
    }

 

  这样看来,可能会有一些疑问,编译器怎么决定要使用的拓展方法?怎么个“非请勿来”?

    首先,如果总是会检测一下是不是实例方法;

    如果不是,就会去查一个合适的拓展方法。它会检查当前的、引用的所有拓展方法。 

tips:为了决定是否使用一个拓展方法,编译器必须能区分拓展方法与某静态类中恰好具有合适签名的其他方法。为此,它会检查类和方法是否具有system.runtime.compilerservices.extensionattribute这个特性(它是.net3.5新增的)。

 

 

  顺带一提,前面提及的inputsimulator类确实这样实现的,思想上是一致的。

    public class keyboardsimulator : ikeyboardsimulator
    {
        ...
        public ikeyboardsimulator keypress(virtualkeycode keycode)
        {
            var inputlist = new inputbuilder().addkeypress(keycode).toarray();
            sendsimulatedinput(inputlist);
            return this;
        }
        ...
    }

 

 

1.2 lambda筛选与链接

  linq里面.where().select().orderby().等等的“点点点”,就是基于拓展方法的思路。

     var list = new list<string> { "a", "b", "c", "d", "a", "b", "c", "d", "a", "a" };
     list = list.where(a => a.equals("a")).reverse().tolist();
     list.foreach(a => console.writeline(a));

 

  在where()点击f12,见:

  publicstatic ienumerable<tsource> where<tsource>(this ienumerable<tsource> source, func<tsource, bool> predicate);

 

    public static ienumerable<tsource> where<tsource>(this ienumerable<tsource> source, func<tsource, bool> predicate)
    {
      if (source == null)
        throw error.argumentnull(nameof (source));
      if (predicate == null)
        throw error.argumentnull(nameof (predicate));
      if (source is enumerable.iterator<tsource>)
        return ((enumerable.iterator<tsource>) source).where(predicate);
      if (source is tsource[])
        return (ienumerable<tsource>) new enumerable.wherearrayiterator<tsource>((tsource[]) source, predicate);
      if (source is list<tsource>)
        return (ienumerable<tsource>) new enumerable.wherelistiterator<tsource>((list<tsource>) source, predicate);
      return (ienumerable<tsource>) new enumerable.whereenumerableiterator<tsource>(source, predicate);
    }

 

  另外有一点值得提,where()返回的是重新new的集合,占据内存空间的。

 

  这篇写得短一些,主要觉得讲的内容还是保持内容一致性的好,关于linq的学习,下一篇继续吧。 

 

 

注释:

[1] 自 https://archive.codeplex.com/?p=inputsimulator 

[2] 自《深入理解c#》(第3版)jon skeet 著  姚琪琳 译

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网