如何找到对象的哪个属性抛出异常C#

时间:2013-02-21 10:59:11

标签: c# .net exception .net-4.0

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

4 个答案:

答案 0 :(得分:1)

我会使用Int32.TryParse代替,然后您可以显式处理解析失败。

public static int StringToInt(this string number)
        {
            try
            {
                int result;
                if (!Int32.TryParse(number, out result))
                {
                    // handle the parse failure
                }
                return result;
            }
        }

答案 1 :(得分:0)

public static int StringToInt(this Numbers number,
 Expression<Func<Numbers, string>> prop)
{
    try
    {
        return Convert.ToInt32(prop.Compile()(number));
    }
    catch (Exception ex)
    {
        var expression = (MemberExpression)prop.Body;
        string name = expression.Member.Name;
        throw new MissingMemberException(string.Format("Invalid member {0}", name));
    }
}

并称之为:

var num = numbers.StringToInt(p=>p.Num1);

答案 2 :(得分:0)

为什么不在调用期间简单地向方法提供所有需要的数据?原理图(您可以扩展它):

public static int ToInt(string number, string info)
{
    try
    {
        // ...
    }
    catch(Exception e)
    {
        MessageBox.Show(info);
    }
}

// and usage
string str1 = "123";
int n = ToInt(str1, "Trying to parsing str1");

答案 3 :(得分:0)

注意

我正在回答基于.NET 4.5的这个问题,因为这个问题没有特定框架版本的标签。我在这里留下答案,因为它可能对将来使用.NET 4.5的访问者有用。

我想说你的代码示例非常难看,因为你可以通过使用int.TryParse来解决这个问题,但是我想你想展示一个普遍的情况(糟糕的选择)而你只是想知道扩展方法的调用者名称:检查4.5版.NET Framework中引入的[CallerMemeberNameAttribute]

例如,无论是在扩展方法还是常规方法中,都可以这样做:

public void Method([CallerMemberName] string callerName)
{
}

CLR会将输入参数设置为调用者名称!

相关问题