我有這樣的課。 (這只是例子)構造函數拋出的異常以及實例和內存分配會發生什麼?
public class NewTest
{
public int I { get; set; }
public NewTest()
{
I = 10;
throw new ApplicationException("Not Possible");
}
}
現在,如果我使用類這樣
NewTest t = new NewTest();
在上面行NewTest構造函數拋出異常變量t從未指定任何值constuctor之前得到完成它拋出異常,但根據測試以及每個其他問題(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確實喜歡沒有被引用的對象。對於所有它關心,它認爲這是你可以寫的最有效的代碼:)好吧,現在不計算它也必須收集異常對象。你在這裏煩惱一個不存在的問題。 –