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

4 に答える 4

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;
            }
        }
于 2013-02-21T11:02:40.447 に答える
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");
于 2013-02-21T11:35:39.810 に答える
0

ノート

質問には特定のフレームワーク バージョンのタグがなかったため、.NET 4.5 に基づいてこの質問に回答していました。.NET 4.5 を使用する将来の訪問者に役立つ可能性があるため、ここに回答を残します。

を使用してこの問題を克服できるため、コードサンプルは非常に醜いと言いint.TryParseたいのですが、一般化されたケース(悪い選択)を示したいと思い、拡張メソッドの呼び出し元の名前を知りたいだけだと思います:4.5 バージョンの .NET Framework で導入されたものを確認します。[CallerMemeberNameAttribute]

たとえば、拡張メソッドまたは通常のメソッドで、次のようにします。

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

そして、CLR は呼び出し元の名前で入力パラメーターを設定します!

于 2013-02-21T11:37:20.750 に答える
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);
于 2013-02-21T11:22:42.393 に答える