【发布时间】:2017-04-03 05:13:48
【问题描述】:
我有这样的课。 (这只是例子)
public class NewTest
{
public int I { get; set; }
public NewTest()
{
I = 10;
throw new ApplicationException("Not Possible");
}
}
现在如果我使用这样的类
NewTest t = new NewTest();
在上面的行中,作为 NewTest 构造函数抛出异常变量 t 从不分配任何值,因为在构造函数完成之前它会抛出异常,但根据测试和其他问题 (Why throwing exception in constructor results in a null reference?) 对象被创建。
现在这个对象是在堆中创建的,但它没有任何根变量供参考,所以它会为垃圾收集带来问题吗?或者它是什么东西的内存泄漏?
以下示例可帮助我消除困惑。 另一个例子
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");
}
}
}
【问题讨论】:
-
GC 真的很喜欢没有被引用的对象。不管它关心什么,它认为这是你能写出的最有效的代码 :) 好吧,不计算它现在还必须收集异常对象。您在这里为一个不存在的问题而烦恼。
标签: c# garbage-collection