有人可以解释为什么这在C#.NET 2.0中有效:
Nullable<DateTime> foo;
if (true)
foo = null;
else
foo = new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
......但这不是:
Nullable<DateTime> foo;
foo = true ? null : new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
后一种形式给我一个编译错误"无法确定条件表达式的类型,因为'<null>'和'System.DateTime'之间没有隐式转换."
并不是说我不能使用前者,但第二种风格与我的其余代码更加一致.
考虑到评估时间,以下是两个相当的?
if(condition1)
{
//code1
}
else
{
//code2
}
Run Code Online (Sandbox Code Playgroud)
condition1 ? code1 : code2
或者它们只是语法上的不同?
if-statement operators ternary-operator conditional-operator micro-optimization
我想做这样的事情:
int? l = lc.HasValue ? (int)lc.Value : null;
Run Code Online (Sandbox Code Playgroud)
其中lc是可以为空的枚举类型,比如EMyEnumeration?.所以我想测试lc是否有值,所以如果然后将其int值赋给l,否则l为null.但是当我这样做时,C#抱怨'无法确定条件表达式的错误类型,因为'int'和''之间没有隐式转换.
我怎样才能使它正确?提前致谢!!