3

次のコードがあり、正常に動作します。

var firstChild = token.First as JProperty;
bool isHref = token.Children().Count() == 1
           && firstChild?.Name == "href";

文字列比較で大文字と小文字を区別しないようにしたかったので、次のように変更しました。

var firstChild = token.First as JProperty;

bool isHref = token.Children().Count() == 1
           && firstChild?.Name.Equals("href", StringComparison.OrdinalIgnoreCase);

今、コンパイラは私にエラーを与えています:

演算子 && は、タイプ 'bool' および 'bool?' のオペランドには適用できません。

false のように合体することでエラーを修正できます

bool isHref = token.Children().Count() == 1
         && (firstChild?.Name.Equals("href", StringComparison.OrdinalIgnoreCase) ?? false);

しかし、コンパイラが最初の null 条件構文を好まない理由が気になります。

4

2 に答える 2

5

要点を簡単に説明しましょう。

string x = null, y = null;

// this is null.  b1 is bool?
var b1 = x?.Equals(y); 

// b2 is bool
// this is true, since the operator doesn't require non-null operands
var b2 = x == y;

基本的.Equals()に、操作には null 以外のオブジェクトが必要です。==これは、静的にバインドされ、動的にディスパッチされない とは異なります。

于 2015-08-24T19:21:36.983 に答える