Cascading null reference exception check?

自作多情 提交于 2019-12-10 10:55:24

问题


Is there a way to do a generic cascading null reference check in c#?

What i am trying to achieve is if i am trying to access a string variable which is part of a class C, which is inturn in class B, which is in A.

A.B.C.str

And that i am passed in A, i will have to check to see if A is null, then check if B is null, then check is C is null and then access str.

Is it possible to have some method where - we can potentially pass in, A and A.B.C.str and it return null is anything was null or value of str if everything existed correctly.


回答1:


There is no built in way to do this yet, however in C# 6.0 we are expecting a 'safe navigation' operator, see this post by Jerry Nixon

It will look something like this:

var g1 = parent?.child?.child?.child; 
if (g1 != null) // TODO



回答2:


There is no built-in possibility in c#, but you can use something like this http://www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad

It involves declaring a function thusly:

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);
}

which you can then call like this:

string postCode = this.With(x => person)
                      .With(x => x.Address)
                      .With(x => x.PostCode);


来源:https://stackoverflow.com/questions/24417897/cascading-null-reference-exception-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!