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?);
}
あなたは 'のx == 11を選択した結果をどう思います&&!y'はありますか?そして、これまで価値がないと思うのはなぜですか? – mason
@mason - 警告は 'result.HasValue'行にあると主張され、' result'は 'bool? '型です。 – Lee
@JonSkeet - はい、ありがとうございます。 – Lee