有没有办法找出对象的哪个属性引发了异常。我有一个具有 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 框架 4.0。请建议。