zoukankan      html  css  js  c++  java
  • 比较C#中的委托和Ruby中的block对象

    Ruby中,所谓带块(block)的方法是指对控制结构的抽象,最初设计是用于对循环进行抽象,所以又称迭代器。
    语法:method_name do...end 或 method_name {}

     1#块调用
     2def foo
     3  print yield(5)
     4end
     5
     6foo {|a|
     7    if a > 0
     8        "positive"
     9    elsif a < 0
    10        "negative"
    11    else
    12        "zero"
    13    end
    14}
    15
    16foo()
    17
    18#使用了proc(过程对象)的块调用
    19quux = proc {|a|
    20    if a > 0
    21        "positive"
    22    elsif a < 0
    23        "negative"
    24    else
    25        "zero"
    26    end
    27}
    28
    29def foo(p)
    30    print p.call(5)
    31end
    32
    33foo(quux)
     1//传统委托
     2public delegate string fooDelegate(int a);
     3public string foo(int a)
     4{
     5    if(a > 0)
     6        return "positive";
     7    else if(a < 0)
     8        return "negative";
     9    return "zero";
    10}

    11fooDelegate myD1 = new fooDelegate(foo);
    12Console.WriteLine(myD1(5));
    13
    14//匿名委托 C# 2.0
    15public delegate string fooDelegate(int a);
    16fooDelegate myD1 = delegate(int a)
    17{
    18    if(a > 0)
    19        return "positive";
    20    else if(a < 0)
    21        return "negative";
    22    return "zero";
    23}

    24Console.WriteLine(myD1(5));
    // Action/Func委托 + lambda表达式 C# 3.0
    Action<Func<int, string>> foo = (func)=>{
        Console.WriteLine(func(5));
    };
    Action qoo = () => {
        foo((a) => {
            if(a > 0)
                return "positive";
            else if(a < 0)
                return "negative";
            return "zero";
        });
    };
    qoo();
    
    
    Func<int, string> quux = (a) =>{
        if(a > 0)
            return "positive";
        else if(a < 0)
            return "negative";
        return "zero";
    };
    Action<Func<int, string>> foo = (func)=>{
        Console.WriteLine(func(5));
    };
    foo(quux);
  • 相关阅读:
    (转)6 个重构方法可帮你提升 80% 的代码质量
    (转)卸载和安装LINUX上的JDK
    (转)一些国外优秀的elasticsearch使用案例
    (转)Redis 集群方案
    (转)理想化的 Redis 集群
    (转)Hprose与WCF在云计算平台Azure上的对决
    (转).NET技术+25台服务器怎样支撑世界第54大网站
    Hbase split的过程以及解发条件
    test
    HTTP和HTTPS详解
  • 原文地址:https://www.cnblogs.com/yicone/p/407188.html
Copyright © 2011-2022 走看看