您的位置:首页 > 编程语言 > Ruby

比较C#中的委托和Ruby中的block对象

2006-05-23 15:37 405 查看
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
"negative"
else
"zero"
end
}

foo()

#使用了proc(过程对象)的块调用
quux = proc {|a|
if a > 0
"positive"
elsif a < 0
"negative"
else
"zero"
end
}

def foo(p)
print p.call(5)
end

foo(quux)

1//传统委托
2public delegate string fooDelegate(int a);
3public string foo(int a)
4fooDelegate myD1 = new fooDelegate(foo);
Console.WriteLine(myD1(5));

//匿名委托 C# 2.0
public delegate string fooDelegate(int a);
fooDelegate myD1 = delegate(int a)
Console.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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: