オブジェクトのどのプロパティが例外をスローしたかを調べる方法はありますか。私は3つのプロパティを持つクラスを持っています。クラスの特定のプロパティが間違っているというメッセージをユーザーに伝えたいです。
public class Numbers
{
public string Num1 { get; set; }
public string Num2 { get; set; }
public string Num3 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var numbers = new Numbers() { Num1 = "22", Num2 = "err", Num3 = "33" };
// Call an extension method which tries convert to Int
var num = numbers.Num1.StringToInt();
num = numbers.Num2.StringToInt();
num = numbers.Num3.StringToInt();
Console.WriteLine(num);
Console.ReadLine();
}
}
public static class SampleExtension
{
static StackTrace stackTrace = new StackTrace(true);
// Extension method that converts string to Int
public static int StringToInt(this string number)
{
try
{
// Intentionally used 'Convert' instead of 'TryParse' to raise an exception
return Convert.ToInt32(number);
}
catch (Exception ex)
{
// Show a msg to the user that Numbers.Num2 is wrong. "Input string not in correct format"
var msg = stackTrace.GetFrame(1).GetMethod().ToString();
msg = ex.Message;
msg += ex.StackTrace;
throw;
}
}
}
sting を int に変換する拡張メソッドを使用しています。そして、拡張メソッド自体で間違ったプロパティをキャッチする方法を探しています。私は.Net Framework 4.0を使用しています。提案してください。