◯ Action 型にメソッドを代入して Invoke で呼び出し
◯ Action 型にメソッドを代入して DynamicInvoke で呼び出し
◯ リフレクションで呼び出し
それぞれの方法でメソッドを呼び出す
呼び出されるメソッドは例外を発生させる
public void Button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("standard call+++++++++");
try
{
this.method1();
}
catch (Exception ex)
{
Console.WriteLine($"catch at Button_Click: {ex.Message}");
Console.WriteLine($"-- inner exception: {ex.InnerException?.Message}");
}
Console.WriteLine("\ndelegate call+++++++");
try
{
Action fn = this.method1;
fn.Invoke();
}
catch (Exception ex)
{
Console.WriteLine($"catch at Button_Click: {ex.Message}");
Console.WriteLine($"-- inner exception: {ex.InnerException?.Message}");
}
Console.WriteLine("\ndelegate dynamic call+++++++");
try
{
Action fn = this.method1;
fn.DynamicInvoke(null);
}
catch (Exception ex)
{
Console.WriteLine($"catch at Button_Click: {ex.Message}");
Console.WriteLine($"-- inner exception: {ex.InnerException?.Message}");
}
Console.WriteLine("\nreflection call+++++++");
try
{
this.GetType().GetMethod("method1").Invoke(this, null);
}
catch (Exception ex)
{
Console.WriteLine($"catch at Button_Click: {ex.Message}");
Console.WriteLine($"-- inner exception: {ex.InnerException?.Message}");
}
}
public void method1()
{
try
{
method2();
}
catch (Exception ex)
{
Console.WriteLine($"catch method1: {ex.Message}");
Console.WriteLine($"-- inner exception: {ex.InnerException?.Message}");
throw;
}
}
public void method2()
{
throw new Exception("えらー");
}
結果は下 2 つの動的な呼び出しだと catch した例外は TargetInvocationException になってる
その InnerException に呼び出したメソッドで実際に発生した例外が入ってる
standard call+++++++++
catch method1: えらー
-- inner exception:
catch at Button_Click: えらー
-- inner exception:
delegate call+++++++
catch method1: えらー
-- inner exception:
catch at Button_Click: えらー
-- inner exception:
delegate dynamic call+++++++
catch method1: えらー
-- inner exception:
catch at Button_Click: 呼び出しのターゲットが例外をスローしました。
-- inner exception: えらー
reflection call+++++++
catch method1: えらー
-- inner exception:
catch at Button_Click: 呼び出しのターゲットが例外をスローしました。
-- inner exception: えらー