あなたがラッシュについて考える前に? null合体演算子:1の線形、美しさとC#でnullの場合に値を割り当てるクリーンな方法は?
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
myParentまたはobjPropertyがnullであるかどうか、それもstrPropertyの評価に到達する前に例外がスローされますとき、ここで問題があります。
次の余分なヌルcheckingsを避けるために:
if (myParent != null)
{
if (objProperty!= null)
{
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
}
}
私は、一般的にこのようなものを使用します。
string result = ((myParent ?? new ParentClass())
.objProperty ?? new ObjPropertyClass())
.strProperty ?? "default string value if strObjProperty is null";
オブジェクトがnullであれば、それが唯一のことができるようにするために、新しいものを作成し、プロパティにアクセスします。
非常にきれいではありません。
私は '???'演算子:
string result = (myParent.objProperty.strProperty) ??? "default string value if strObjProperty is null";
...代わりにデフォルト値を返すためにかっこの内部から "null"が残っていても問題ありません。
あなたのヒントありがとうございます。
ルック:
IfNullOrEmpty
だけであるを。 – Luaan