C# Lambda 对象范围

发布于 2024-10-19 13:53:11 字数 373 浏览 1 评论 0原文

我刚刚在 Lambda 上观看了 TekPub 视频,代码类似于:

class Foo{
   void DoSomething();
}

static void Bar(Foo item, Action<Foo> action){
   return action.Invoke(item);
}

然后在 Main 中:

Bar(new Foo(), x=>x.DoSomething();

我的问题是,Foo 对象是否在调用 Bar< 的范围内/代码>?调用该方法后对象是否会被销毁?

谢谢。

I have just been watching a TekPub video on Lambda's and the code was similar to such:

class Foo{
   void DoSomething();
}

static void Bar(Foo item, Action<Foo> action){
   return action.Invoke(item);
}

And then within Main:

Bar(new Foo(), x=>x.DoSomething();

My question is, is the Foo object just within scope for that call to Bar? Is the object destroyed once that method has been called?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

無處可尋 2024-10-26 13:53:11

在这种特殊情况下,发生的情况是 foo 对象与您的委托一起传递给 Bar 方法。 Bar 方法调用该操作,该操作对 foo 调用 DoSomething,然后返回。

由于方法 Bar 不会返回您传递给它的对象,也不会返回调用委托的结果,并且相关代码不会在任何地方存储对象引用,因此您创建的对象 foo一旦 Bar 返回,现在就有资格进行垃圾回收。

具体何时回收该对象的内存取决于 GC 运行的时间,但在 Bar 返回后的某个时刻,分配给该对象的内存将被回收。它不会立即发生,即。作为酒吧回归的一部分。

In this particular case, what happens is that the foo object is passed, along with your delegate, to the Bar method. The Bar method invokes the action, which calls DoSomething on foo, then returns.

Since the method Bar doesn't return the object you pass to it, nor the result of calling the delegate, and the code in question doesn't store the object reference anywhere, the object foo that you created is now eligible for garbage collection once Bar returns.

Exactly when memory for that object will be reclaimed depends on when GC runs, but at some point after Bar has returned, the memory allocated to the object will be reclaimed. It will not happen immediately, ie. as part of Bar returning.

凤舞天涯 2024-10-26 13:53:11

是的,一旦方法返回,它就应该被处理掉,因为没有任何操作产生额外的引用。

然而,这不是一般情况,它实际上取决于该方法用它做什么 - 如果它创建一个引用内联创建的新对象,它可以在方法返回后存活。在这种情况下,Action 可以将 Foo 添加到字典或某种列表中,这意味着它不会被垃圾收集,因为仍然有对其的引用。

Yes, it should be disposed of once the method returns as none of the operations produce an additional reference.

However, this isn't the general case, it really depends on what the method does with it - if it creates a new object with a reference to the inline created one, it can live after the method returned. In this case the Action<T> could add the Foo to a dictionary or list of some sort which would mean that it won't be garbage collected, as there are still references to it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文