0

より一般的には、パラメータ化されるタイプのターゲットがトップレベルのプロパティではない場合に、どのように汎用ルーチンを作成するのか疑問に思っています。

具体的には、次の2つの機能から重複を排除することに取り組んでいます。

    private static string ExceptionMessage(Exception e)
    {
        string result = string.Empty;
        Exception exception = e;
        while (exception != null)
        {
            if (e.Message != null)
            {
                if (result.Length > 0)
                {
                    result += Separator;
                }
                result += exception.Message;
            }
            exception = exception.InnerException;
        }
        return result;
    }

    private static string Tag(Exception e)
    {
        string result = string.Empty;
        Exception exception = e;
        while (exception != null)
        {
            if (e.TargetSite != null)
            {
                if (result.Length > 0)
                {
                    result += Separator;
                }
                result += exception.TargetSite.Name;
            }
            exception = exception.InnerException;
        }
        return result;
    }
4

1 に答える 1

2

ジェネリックスを介してこれを明示的に行う方法は(現在)ありません。関数にブール引数を送信することは、探しているものではないと思います。

以下の例のように、必要なExceptionインスタンスの一部を抽出するクロージャを渡すことで、これを回避できます。

private static string AggregateException(Exception e, Func<Exception,string> getPart){
        string result = string.Empty;
        Exception exception = e;
        while (exception != null)
        {
            if (e.Message != null)
            {
                if (result.Length > 0)
                {
                    result += Separator;
                }
                result += getPart(exception);
            }
            exception = exception.InnerException;
        }
        return result;
}

使用例:

    string msg = AggregateException(myEx, (ex) => ex.Message);
    string tag = AggregateException(myEx, (ex) => ex.TargetSite.Name);
于 2012-05-21T19:21:46.147 に答える