C# 中委托的这种用法的名称是什么?
这是一个术语问题。在 C# 中,我可以这样做:
delegate Stream StreamOpenerDelegate(String name);
void WorkMethod(StreamOpenerDelegate d)
{
// ...
}
void Exec1()
{
WorkMethod((x) =>
{
return File.OpenRead(x);
});
}
void Exec2()
{
StreamOpenerDelegate opener = (x) =>
{
return File.OpenRead(x);
};
WorkMethod(opener);
}
Q1
Exec1() 方法演示了匿名委托的使用,对吗?
第二季度
在 Exec2() 内部,将opener
被视为匿名代表?它确实有一个名字。如果它不是匿名代表,我应该称呼它什么呢?这个语法有名字吗? “指定匿名代表?”持有匿名委托的局部变量?
This is a terminology question. In C#, I can do this:
delegate Stream StreamOpenerDelegate(String name);
void WorkMethod(StreamOpenerDelegate d)
{
// ...
}
void Exec1()
{
WorkMethod((x) =>
{
return File.OpenRead(x);
});
}
void Exec2()
{
StreamOpenerDelegate opener = (x) =>
{
return File.OpenRead(x);
};
WorkMethod(opener);
}
Q1
The Exec1() method demonstrates the use of an anonymous delegate, correct?
Q2
Inside Exec2(), would opener
be considered an anonymous delegate? It does have a name. If it's not an anonymous delegate, what should I call it? Is there a name for this syntax? "named anonymous delegate?" a local variable holding an anonymous delegate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Q1:没有“匿名委托”这样的术语(在 C# 语言规范中) - 但这使用 lambda 表达式,这是一种匿名函数。有关详细信息,请参阅 C# 语言规范第 7.14 节。
Q2:
opener
是一个变量。该变量被赋予使用 lambda 表达式创建的值。创建后,委托只是 StreamOpenerDelegate 的一个实例。换句话说,lambda 表达式、匿名函数和匿名方法的概念是源代码概念,而不是执行时间概念。 CLR 并不关心您如何创建委托。顺便说一句,您的两个 lambda 表达式都可以更简洁地表达 - 更少的括号等:
或者您可以只使用方法组转换:
Q1: There's no such term as "anonymous delegate" (in the C# language specification) - but this uses a lambda expression which is one kind of anonymous function. See section 7.14 of the C# language specification for details.
Q2:
opener
is a variable. The variable is assigned a value created using a lambda expression. After it's been created, the delegate is just an instance ofStreamOpenerDelegate
. In other words, the concepts of lambda expression, anonymous function and anonymous method are source code concepts rather than execution time concepts. The CLR doesn't care how you created the delegate.By the way, both of your lambda expressions can be expressed more concisely - fewer parentheses etc:
alternatively you could just use a method group conversion:
不,不。
A1:此功能是 C# 3.0 的新增功能,称为lambda 表达式。 C# 2.0 有一个类似的功能,称为匿名方法;例如:
A2:
opener
是一个恰好包含 lambda 表达式的常规变量。顺便说一下,只接受一个参数的 lambda 表达式不需要括号。此外,仅包含 return 语句的 lambda 表达式不需要大括号。
例如:
No and no.
A1: This feature is new to C# 3.0 and is called a lambda expression. C# 2.0 has a similar feature called anonymous methods; for example:
A2:
opener
is a regular variable that happens to hold a lambda expression.By the way, a lambda expression that takes exactly one parameter doesn't need parentheses. Also, a lambda expression that consists only of a return statement doesn't need braces.
For example: