4

次のコードがあります。

protected IEnumerable<string> GetErrorsFromModelState() {

    var exceptions = ModelState.SelectMany(x => x.Value.Errors
        .Select(error => error.Exception.Message));

    var errors = ModelState.SelectMany(x => x.Value.Errors
        .Select(error => error.ErrorMessage));

    return exceptions.Union(errors);
}

次の場合に nullReference 例外を発生させないようにする方法はありますか?

error.Exception is null  or if error.Exception.Message is null

どちらのケースでも問題が発生しており、両方のケースで IsNullOrEmpty チェックを使用してこれをコーディングする方法がわかりません。

4

4 に答える 4

2

どうですか

protected IEnumerable<string> GetErrorsFromModelState()
{        
    var exceptions = ModelState.SelectMany(x => x.Value.Errors
                            .Where(error => (error != null) && 
                                            (error.Exception != null) &&
                                            (error.Exception.Message != null))
                            .Select(error => error.Exception.Message));

    var errors = ModelState.SelectMany(x => x.Value.Errors
                            .Where(error => (error != null) && 
                                            (error.ErrorMessage != null))
                            .Select(error => error.ErrorMessage));

    return exceptions.Union(errors);
}
于 2012-09-01T09:16:30.057 に答える
2

May be Monadを使用できます。最初に静的クラスを作成しWith 、そのクラスに拡張メソッドを配置してから、単にWithメソッドを使用します。リンクには、他にも役立つ同様のタイプがいくつかあります。

public static TResult With<TInput, TResult>(this TInput o, 
       Func<TInput, TResult> evaluator)
       where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}

そしてそれを簡単に使用してください:

var exceptions = ModelState.SelectMany(x => x.With(y=>y.Value).With(z=>z.Errors))
        .Select(error => error.With(e=>e.Exception).With(m=>m.Message));

更新:より明確にするために(同様のサンプルがリンクにも存在します)、Personクラス階層があると仮定します:

public class Person
{
   public Address Adress{get;set;}
}

public class Address
{
   public string PostCode{get;set;}
}

ここで、個人に関連する郵便番号を取得したいのですが、入力された個人が null かどうかはわかりません。

var postCode = 
// this gives address or null, if either person is null or its address
person.With(x=>x.Address) 
// this gives post code or returns null, 
// if previous value in chain is null or post code is null 
      .With(x=>x.PostCode);
于 2012-09-01T09:16:51.800 に答える
2

選択する前に a を追加して、.Where(error.Exception != null && error.Exception.Message != null)必要な値がないもののみを含めますnull

于 2012-09-01T09:12:05.160 に答える
1

次に、null を除外するには.Where(error => error.Exception != null) (Exceptionオブジェクトには常に null 以外のメッセージが含まれている必要があるため、例外が発生した場合に検出して修正するバグとして数えます)。

そのような場合に異なる振る舞いをするには、例えば.Select(error => error.Exception == null ? "No Error" : error.Exception.Message).

于 2012-09-01T09:17:42.277 に答える