dot*_*tep 4 c# garbage-collection
我有这样的课.(这只是一个例子)
public class NewTest
{
public int I { get; set; }
public NewTest()
{
I = 10;
throw new ApplicationException("Not Possible");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我使用这样的类
NewTest t = new NewTest();
Run Code Online (Sandbox Code Playgroud)
在上面的行中,作为NewTest构造函数抛出异常变量t永远不会像constuctor之前那样分配任何值,它会抛出异常,但是根据测试以及其他问题(为什么在构造函数中抛出异常导致空引用?)对象被创建.
现在这个对象是在Heap中创建的,但它不包含任何根变量以供参考,所以它是否会为垃圾收集创建问题?或是内存泄漏了什么?
以下示例帮助我清除我的困惑.另一个例子
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NewMethod();
System.GC.Collect();
Console.WriteLine("Completed");
Console.ReadLine();
}
private static void NewMethod()
{
Object obj = null;
try
{
Console.WriteLine("Press any key to continue");
Console.ReadLine();
NewTest t = new NewTest(out obj);
}
catch
{
Console.WriteLine("Exception thrown");
}
try
{
Console.WriteLine("Press any key to continue");
Console.ReadLine();
NewTest1 t = new NewTest1();
}
catch
{
Console.WriteLine("Exception thrown");
}
Console.WriteLine("Press any key to continue");
Console.ReadLine();
System.GC.Collect();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
public class NewTest1
{
public int I { get; set; }
public NewTest1()
{
I = 10;
throw new ApplicationException("Not Possible");
}
}
public class NewTest
{
public int I { get; set; }
public NewTest(out Object obj)
{
obj = this;
I = 10;
throw new ApplicationException("Not Possible");
}
}
}
Run Code Online (Sandbox Code Playgroud)
其他答案都是正确的; 我将向他们添加一个有趣的事实,即构造函数抛出的最终对象仍然是最终的.这意味着终结器可以对构造函数未正常完成的对象进行操作.终结器不能假定对象在完成时初始化.这是为什么难以编写正确的终结器的一长串原因中的另一个.
| 归档时间: |
|
| 查看次数: |
806 次 |
| 最近记录: |