是否存在委托语法优先于匿名方法的lambda表达式的情况?

时间:2022-09-07 11:12:50

With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.

随着lambda表达式(内联代码)等新功能的出现,它是否意味着我们不再需要使用委托或匿名方法了?在我看过的几乎所有样本中,都是使用新语法进行重写。

Any place where we still have to use delegates and lambda expressions won't work?

我们仍然需要使用delegates和lambda表达式的任何地方都不起作用?

7 个解决方案

#1


27  

Yes there are places where directly using anonymous delegates and lambda expressions won't work.

是的,有些地方直接使用匿名委托,lambda表达式不起作用。

If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.

如果某个方法采用无类型的Delegate,那么编译器不知道要解析匿名委托/ lambda表达式的内容,您将收到编译器错误。

public static void Invoke(Delegate d)
{
  d.DynamicInvoke();
}

static void Main(string[] args)
{
  // fails
  Invoke(() => Console.WriteLine("Test"));

  // works
  Invoke(new Action(() => Console.WriteLine("Test")));

  Console.ReadKey();
}

The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".

失败的代码行将得到编译器错误“无法将lambda表达式转换为类型'System.Delegate',因为它不是委托类型”。

#2


8  

lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:

lambda是匿名委托的快捷方式,但您将始终使用委托。委托指定方法签名。你可以这样做:

 delegate(int i) { Console.WriteLine(i.ToString()) }

can be replaced with

可以替换为

f => Console.WriteLine(f.ToString())

#3


7  

Lambda expression is not (and was not meant to be) a silver bullet that would replace (hide) delegates. It is great with small local things like:

Lambda表达式不是(并不意味着)一个替代(隐藏)代表的银弹。当地的小东西很棒,比如:

List<string> names = GetNames();
names.ForEach(Console.WriteLine);
  1. it makes code more readable thus simple to understand.
  2. 它使代码更易读,因此易于理解。

  3. It makes code shorter thus less work for us ;)
  4. 它使代码更短,因此对我们来说工作量减少;)

On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:

另一方面,滥用它们非常简单。长或/和复杂的lambda表达式倾向于:

  1. Hard to understand for new developers
  2. 新开发人员很难理解

  3. Less object oriented
  4. 面向对象较少

  5. Much harder to read
  6. 更难阅读

So “does it mean we don’t have to use delegates or anonymous methods anymore?” No – use Lambda expression where you win time/readability otherwise consider using delegates.

所以“这是否意味着我们不再需要使用委托或匿名方法?”否 - 使用Lambda表达式,您可以在其中赢得时间/可读性,否则请考虑使用委托。

#4


3  

Lambda expressions are just "syntactic sugar", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.

Lambda表达式只是“语法糖”,编译器将为您生成适当的委托。您可以使用Lutz Roeder的Reflector进行调查。

#5


3  

Lamda's are just syntactic sugar for delegates, they are not just inline, you can do the following:

Lamda只是代表们的语法糖,他们不只是内联,你可以做到以下几点:

s.Find(a =>
{
    if (a.StartsWith("H"))
        return a.Equals("HI");
    else
        return !a.Equals("FOO");
});

And delegates are still used when defining events, or when you have lots of arguments and want to actually strongly type the method being called.

并且在定义事件时,或者当您有大量参数并希望实际强类型化被调用的方法时,仍会使用委托。

#6


3  

Delegate have two meanings in C#.

代表在C#中有两个含义。

The keyword delegate can be used to define a function signature type. This is usually used when defininge the signature of higher-order functions, i.e. functions that take other functions as arguments. This use of delegate is still relevant.

关键字delegate可用于定义函数签名类型。这通常在定义高阶函数的签名时使用,即将其他函数作为参数的函数。代表的这种使用仍然相关。

The delegate keyword can also be used to define an inline anonymous function. In the case where the function is just a single expression, the lambda syntax is a simpler alternative.

delegate关键字也可用于定义内联匿名函数。在函数只是单个表达式的情况下,lambda语法是一种更简单的替代方法。

#7


2  

One not so big advantage for the older delegate syntax is that you need not specify the parameters if you dont use it in the method body. From msdn

旧代理语法的一个不那么大的优点是,如果您不在方法体中使用它,则无需指定参数。来自msdn

There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.

有一种情况是匿名方法提供lambda表达式中没有的功能。匿名方法使您可以省略参数列表。这意味着可以将匿名方法转换为具有各种签名的委托。 lambda表达式无法做到这一点。

For example you can do:

例如,你可以这样做:

Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS

While this fails:

虽然这失败了:

Action<int> a = => { }; //omitted parameter, doesnt compile.

This technique mostly comes handy when writing event-handlers, like:

在编写事件处理程序时,这种技术通常很方便,例如:

button.onClicked += delegate { Console.WriteLine("clicked"); };

This is not a strong advantage. It's better to adopt the newer syntax always imho.

这不是一个强大的优势。最好采用新的语法总是imho。

#1


27  

Yes there are places where directly using anonymous delegates and lambda expressions won't work.

是的,有些地方直接使用匿名委托,lambda表达式不起作用。

If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.

如果某个方法采用无类型的Delegate,那么编译器不知道要解析匿名委托/ lambda表达式的内容,您将收到编译器错误。

public static void Invoke(Delegate d)
{
  d.DynamicInvoke();
}

static void Main(string[] args)
{
  // fails
  Invoke(() => Console.WriteLine("Test"));

  // works
  Invoke(new Action(() => Console.WriteLine("Test")));

  Console.ReadKey();
}

The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".

失败的代码行将得到编译器错误“无法将lambda表达式转换为类型'System.Delegate',因为它不是委托类型”。

#2


8  

lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:

lambda是匿名委托的快捷方式,但您将始终使用委托。委托指定方法签名。你可以这样做:

 delegate(int i) { Console.WriteLine(i.ToString()) }

can be replaced with

可以替换为

f => Console.WriteLine(f.ToString())

#3


7  

Lambda expression is not (and was not meant to be) a silver bullet that would replace (hide) delegates. It is great with small local things like:

Lambda表达式不是(并不意味着)一个替代(隐藏)代表的银弹。当地的小东西很棒,比如:

List<string> names = GetNames();
names.ForEach(Console.WriteLine);
  1. it makes code more readable thus simple to understand.
  2. 它使代码更易读,因此易于理解。

  3. It makes code shorter thus less work for us ;)
  4. 它使代码更短,因此对我们来说工作量减少;)

On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:

另一方面,滥用它们非常简单。长或/和复杂的lambda表达式倾向于:

  1. Hard to understand for new developers
  2. 新开发人员很难理解

  3. Less object oriented
  4. 面向对象较少

  5. Much harder to read
  6. 更难阅读

So “does it mean we don’t have to use delegates or anonymous methods anymore?” No – use Lambda expression where you win time/readability otherwise consider using delegates.

所以“这是否意味着我们不再需要使用委托或匿名方法?”否 - 使用Lambda表达式,您可以在其中赢得时间/可读性,否则请考虑使用委托。

#4


3  

Lambda expressions are just "syntactic sugar", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.

Lambda表达式只是“语法糖”,编译器将为您生成适当的委托。您可以使用Lutz Roeder的Reflector进行调查。

#5


3  

Lamda's are just syntactic sugar for delegates, they are not just inline, you can do the following:

Lamda只是代表们的语法糖,他们不只是内联,你可以做到以下几点:

s.Find(a =>
{
    if (a.StartsWith("H"))
        return a.Equals("HI");
    else
        return !a.Equals("FOO");
});

And delegates are still used when defining events, or when you have lots of arguments and want to actually strongly type the method being called.

并且在定义事件时,或者当您有大量参数并希望实际强类型化被调用的方法时,仍会使用委托。

#6


3  

Delegate have two meanings in C#.

代表在C#中有两个含义。

The keyword delegate can be used to define a function signature type. This is usually used when defininge the signature of higher-order functions, i.e. functions that take other functions as arguments. This use of delegate is still relevant.

关键字delegate可用于定义函数签名类型。这通常在定义高阶函数的签名时使用,即将其他函数作为参数的函数。代表的这种使用仍然相关。

The delegate keyword can also be used to define an inline anonymous function. In the case where the function is just a single expression, the lambda syntax is a simpler alternative.

delegate关键字也可用于定义内联匿名函数。在函数只是单个表达式的情况下,lambda语法是一种更简单的替代方法。

#7


2  

One not so big advantage for the older delegate syntax is that you need not specify the parameters if you dont use it in the method body. From msdn

旧代理语法的一个不那么大的优点是,如果您不在方法体中使用它,则无需指定参数。来自msdn

There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.

有一种情况是匿名方法提供lambda表达式中没有的功能。匿名方法使您可以省略参数列表。这意味着可以将匿名方法转换为具有各种签名的委托。 lambda表达式无法做到这一点。

For example you can do:

例如,你可以这样做:

Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS

While this fails:

虽然这失败了:

Action<int> a = => { }; //omitted parameter, doesnt compile.

This technique mostly comes handy when writing event-handlers, like:

在编写事件处理程序时,这种技术通常很方便,例如:

button.onClicked += delegate { Console.WriteLine("clicked"); };

This is not a strong advantage. It's better to adopt the newer syntax always imho.

这不是一个强大的优势。最好采用新的语法总是imho。