3

Possible Duplicate:
Shortcut for “null if object is null, or object.member if object is not null”

I wish there were a way to make this type of test simpler in C#:

if (foo != null &&
    foo.bar != null &&
    foo.bar.baz != null &&
    foo.bar.baz.bat != null)
{
    var bat = foo.bar.baz.bat;
    bat.cat = 5;
    bat.dog = 6;
}

One possible feature that would support this is if statements that supported new variable declarations, e.g.

if (foo != null &&
    (var bar = foo.bar) != null &&
    (var baz = bar.baz) != null &&
    (var bat = baz.bat) != null)
{
    bat.cat = 5;
    bat.dog = 6;
}

The gains may not be obvious here, since the proposed solution is actually longer in this example. But with longer names it would really pay off.

Is there any better way to do this? Any chance of a suggestion like this actually making it into a future version of the language (calling Eric Lippert, come in)?

4

3 に答える 3

2

良い質問ですが、悪い意図です。あなたのコードはデメテルの法則を無視します

于 2011-06-21T23:13:24.813 に答える
2

これはかなり頻繁に要求される機能であり、その結果、この質問は StackOverflow で何度か尋ねられています。見る

「オブジェクトが null の場合は null、オブジェクトが null でない場合は object.member」のショートカット

それについてのいくつかの考えのために。

于 2011-06-21T22:42:14.733 に答える
2

通常、if ステートメント内の式を、ファイルの下部にある独自のメソッドに移動するだけです。

if (CheckBat(foo))
{
    var bat = foo.bar.baz.bat;
    bat.cat = 5;
    bat.dog = 6;
}

... snip ...

private bool CheckBat(MyFoo foo)
{
    return foo != null &&
           foo.bar != null &&
           foo.bar.baz != null &&
           foo.bar.baz.bat != null;
}
于 2011-06-21T21:59:31.230 に答える