我是否需要将MyAction设置为null,以便垃圾收集能够继续使用这些类中的任何一个?
当两个班级的生命周期几乎相同时,我不太关心.当Class1的寿命比Class2长得多或者Class2的寿命比Class1长得多时,我的问题更合适.
这里的代码被删除了.假设Class1和Class2都包含可能影响其生命周期的其他成员和方法.
public class Class1 : IDisposable
{
public Action<string> MyAction { get; set; }
// Is this necessary?
public void Dispose()
{
MyAction = null;
}
}
public class Class2
{
string _result = string.Empty;
public void DoSomething()
{
Class1 myClass1 = new Class1();
myClass1.MyAction = s => _result = s;
myClass1.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud) 我在一个局部变量中存储一个动作,然后我在该局部变量超出范围之后使用.在使用它之前是否有被清理的危险?这是一个例子:
public List<object> GetMaps() {
Action<Customer1, Customer2> baseMap = (Customer1 c1, Customer2 c2) => {
c2.FirstName = c1.FirstName;
};
var list = new List<object>() {
new Action<SpecialCustomer1 c1, SpecialCustomer2 c2>() {
baseMap(c1, c2);
c2.SpecialProperty = c1.SpecialProperty;
},
new Action<SpecialCustomer1 c1, SpecialCustomer2 c2>() {
baseMap(c1, c2);
c2.SpecialProperty2 = c1.SpecialProperty2;
},
};
return list;
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以在此示例中看到该函数正在返回调用的操作列表baseMap. baseMap只是一个局部变量.是否在其他操作中调用它足以让.NET知道不清理它?