好吧,我承認這個代碼對你來說看起來很奇怪,那是因爲這很奇怪。這只是重現行爲的代碼,而不是我想要使用的代碼。無法捕捉異常來自Activator.CreateInstance
class Program
{
static void Main(string[] args)
{
try
{
Activator.CreateInstance(typeof(Func<int>), new object[] { new object(), IntPtr.Zero });
}
catch
{
Console.WriteLine("This won't print!");
}
Console.Write("Actually this will not print either!");
Console.ReadLine();
}
}
不管我試圖抓住什麼異常類型(拋出的實際的異常是一個ArgumentException據我可以告訴)catch塊不會執行裏面的代碼。實際上執行只會停在Activator.CreateInstance行。
只有在構造代表時纔會發生這種情況嗎?你應該爲此使用'Delegate.CreateDelegate'。 – 2010-05-10 14:44:08
它可能只在構造委託時發生,但實際使用的代碼並不知道它試圖創建什麼類型,現在的修正是如果類型繼承自委派,那麼即使嘗試也是「禁止」。 – 2010-05-10 14:50:47