C# 编译的 lambda 表达式实例创建和/或垃圾回收?
考虑以下代码示例:
using System;
using System.Linq.Expressions;
public class Class1<T, Y>
{
public Class1(Expression<Func<T, Y>> mapExpression)
{
GetValue = mapExpression.Compile();
}
public Func<T, Y> GetValue { get; protected set; }
}
public class DataClass
{
public long Data { get; set; }
}
现在假设我在不同的地方创建 Class1 的新实例,例如
var instance1 = new Class1<DataClass, long>(x => x.Data);
var instance2 = new Class1<DataClass, long>(x => x.Data);
,当我这样做时,会发生什么:
- 我得到两个不同的编译函数吗?
- 如果是这样,当 Class1 的实例被垃圾收集时,两个编译函数是否也会被垃圾收集?
- 如果不是,如何避免内存泄漏(假设我无法实际控制 Class1 实例的创建)?
Consider the following code sample:
using System;
using System.Linq.Expressions;
public class Class1<T, Y>
{
public Class1(Expression<Func<T, Y>> mapExpression)
{
GetValue = mapExpression.Compile();
}
public Func<T, Y> GetValue { get; protected set; }
}
public class DataClass
{
public long Data { get; set; }
}
Now suppose that I make in different places new instances of Class1, e.g.
var instance1 = new Class1<DataClass, long>(x => x.Data);
var instance2 = new Class1<DataClass, long>(x => x.Data);
When I do this, what happens:
- Do I get two different compiled functions?
- If so, do the two compiled functions get garbage collected when the instances of Class1 get garbage collected?
- If not, how can I avoid a memory leak (assuming that I can't realistically control the creation of Class1 instances)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)