急いで考えようとする前に?? null 合体演算子:
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
ここでの問題は、myParent または objProperty が null であるかどうかにかかわらず、strProperty の評価に到達する前に例外をスローする場合です。
次の余分な null チェックを回避するには:
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」が何であれ存続し、代わりにデフォルト値を返します。
ヒントをありがとう。