c# - C# 中的 lambda 创建的委托(delegate)的生命周期是多少?

标签 c# delegates lambda

Lambda 很好,因为它们提供 brevity and localityan extra form of encapsulation .您不必编写只使用一次的函数,而是可以使用 lambda。

虽然想知道它们是如何工作的,但我凭直觉认为它们可能只创建一次。这启发了我创建一个允许 to restrict the scope of a class member beyond private 的解决方案通过使用 lambda 作为创建它的范围的标识符到一个特定的范围。

这个实现有效,虽然可能有点矫枉过正(仍在研究中),证明我的假设是正确的。

一个更小的例子:

class SomeClass
{
    public void Bleh()
    {
        Action action = () => {};
    }

    public void CallBleh()
    {
        Bleh();  // `action` == {Method = {Void <SomeClass>b__0()}}
        Bleh();  // `action` still == {Method = {Void <SomeClass>b__0()}}
    }
}

lambda 会返回一个新实例,还是保证它始终相同?

最佳答案

这两种方式都不是保证

根据我对当前 MS 实现的内存:

  • 不捕获任何变量的 lambda 表达式被静态缓存
  • 只捕获“this”的 lambda 表达式可以在每个实例的基础上被捕获,但不是
  • 无法缓存捕获局部变量的 lambda 表达式
  • 两个具有完全相同程序文本的 lambda 表达式没有别名;在某些情况下,它们可能是,但是弄清楚它们可能是的情况会非常复杂
  • 编辑:正如 Eric 在评论中指出的那样,您还需要考虑为通用方法捕获的类型 参数。

编辑:C# 4 规范的相关文本在第 6.5.1 节中:

Conversions of semantically identical anonymous functions with the same (possibly empty) set of captured outer variable instances to the same delegate types are permitted (but not required) to return the same delegate instance. The term semantically identical is used here to mean that execution of the anonymous functions will, in all cases, produce the same effects given the same arguments.

关于c# - C# 中的 lambda 创建的委托(delegate)的生命周期是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6280656/

相关文章:

用于 LINQ 静态方法的 C++/CLI Lambda 选择器

java - 如何将 Iterator 值收集到包含 50 个元素的列表中

.net - 映射表达式<Func<Type1,bool>> 表达式<Func<Type2, bool>>

c# - 在纹理上调用 Resources.Load 不起作用

c# - OneDrive C# sdk 项目集合限制为 200

ios - 一个 View Controller 中的两个 TableView

c# - 使用 Func Delegate 进行错误检查

c# - 如何在 Silverlight 中序列化 List<T>?

c# - Visual Studio 注册表捕获实用程序已停止工作,在 Windows7 中编译 C# 项目时出错

cocoa - 未调用委托(delegate)