2016-05-19 7 views
4

C#でNullable<T>型のSelectとSelectManyの実装を書いて自分自身を楽しんでいます(LINQクエリの理解構文を有効にします)。しかし警告:C#Nullable <T>クエリの解説 - 「式は常に真」警告

public static void Test() 
{ 
    var z1 = 
     from x in 5.Nullable() 
     from y in 6.Nullable() 
     select x + y; 

    var z2 = 
     from x in 3.Nullable() 
     from y in default(DateTime?) 
     select y.Month == x; 

    var result = 
     from x in z1 
     from y in z2 
     select x == 11 && !y; 

    Console.WriteLine(result.HasValue // <-- this expression is "always true" 
     ? result.Value.ToString() 
     : "computation failed"); 
} 

はどのようにそれは、これを請求することができ、私は私が変更した場合hasValueはそのコードが(例えば20にZ1中のxを変更する)偽であるべきであるので、それはそれはまだ、上記のクエリを解釈されていません知っていますか?警告を出します。これはコンパイラのバグですか、間違えましたか?

I私のメソッドの実装は正しいと信じていますが、ここでは参考にしています:

public static T? Nullable<T>(this T x) 
    where T : struct 
{ 
    return x; 
} 

public static U? Select<T, U>(this T? n, Func<T, U> f) 
    where T : struct 
    where U : struct 
{ 
    return n.HasValue 
     ? f(n.Value) 
     : default(U?); 
} 

public static U? SelectMany<T, U>(this T? n, Func<T, U?> f) 
    where T : struct 
    where U : struct 
{ 
    return n.HasValue 
     ? f(n.Value) 
     : default(U?); 
} 

public static V? SelectMany<T, U, V>(this T? n, Func<T, U?> f, Func<T, U, V> g) 
    where T : struct 
    where U : struct 
    where V : struct 
{ 
    if (!n.HasValue) return default(V?); 

    var u = f(n.Value); 
    return u.HasValue 
     ? g(n.Value, u.Value) 
     : default(V?); 
} 
+2

あなたは 'のx == 11を選択した結果をどう思います&&!y'はありますか?そして、これまで価値がないと思うのはなぜですか? – mason

+0

@mason - 警告は 'result.HasValue'行にあると主張され、' result'は 'bool? '型です。 – Lee

+0

@JonSkeet - はい、ありがとうございます。 – Lee

答えて

3

ReSharperの警告は明らかに間違っています。

var z1 = 
    from x in default(int?) 
    from y in 6.Nullable() 
    select x + y; 

if (z1.HasValue) 
{ 
} 

ReSharperのは「常に真」などの条件をマークします:あなたのコードのこの変化を考慮して

enter image description here

しかし、デバッガで、我々はそれが虚偽だとはっきりと見ることができます

enter image description here

私はそれがReSharperのバグだと言います。


(今後の参考のために、it has been submitted by the OP to the issue tracker。)

+0

私はバグレポートを投稿しました。 – kai