为什么这不起作用?看起来像有效的代码.
string cert = ddCovCert.SelectedValue;
int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert);
Display(x);
Run Code Online (Sandbox Code Playgroud)
我该怎么编码呢?该方法采用Nullable.如果下拉列表中选择了一个字符串,我需要将其解析为一个int,否则我想将null传递给该方法.
在代码中进行一些更改我使用下一行:
uint a = b == c ? 0 : 1;
Run Code Online (Sandbox Code Playgroud)
Visual Studio向我显示此错误:
无法将类型'int'隐式转换为'uint'.存在显式转换(您是否错过了演员?)
但是,如果我使用代码:
uint a;
if (b == c)
a = 0;
else
a = 1;
Run Code Online (Sandbox Code Playgroud)
它正常工作,没有任何错误或警告.为什么?
以下代码将无法编译:
string foo = "bar";
Object o = foo == null ? DBNull.Value : foo;
Run Code Online (Sandbox Code Playgroud)
我得到:错误1无法确定条件表达式的类型,因为'System.DBNull'和'string'之间没有隐式转换
要解决这个问题,我必须做这样的事情:
string foo = "bar";
Object o = foo == null ? DBNull.Value : (Object)foo;
Run Code Online (Sandbox Code Playgroud)
这个演员似乎毫无意义,因为这肯定是合法的:
string foo = "bar";
Object o = foo == null ? "gork" : foo;
Run Code Online (Sandbox Code Playgroud)
在我看来,当三元分支具有不同类型时,编译器不会将值自动提供给类型对象...但是当它们属于相同类型时,则自动装箱是自动的.
在我看来,第一个声明应该是合法的......
任何人都可以描述为什么编译器不允许这样做以及为什么C#的设计者选择这样做?我相信这在Java中是合法的......虽然我没有验证这一点.
谢谢.
编辑:我要求理解为什么Java和C#以不同的方式处理这个问题,C#中的场景下发生了什么使得它无效.我知道如何使用三元,而不是寻找一个"更好的方法"来编写示例代码.我理解C#中的三元规则,但我想知道为什么......
编辑(Jon Skeet):删除了"autoboxing"标签,因为这个问题没有涉及拳击.
我想知道这个代码块无法编译的原因.
public decimal? GetDecimalValue(String decimalString)
{
return decimalString.IsNullOrWhiteSpace() ? null : decimal.Parse(decimalString);
}
Run Code Online (Sandbox Code Playgroud)
错误信息: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'decimal'
但是,如果我写出三元语句,那么它就可以了.
public decimal? GetDecimalValueThisOneCompiles(String decimalString)
{
if(decimalString.IsNullOrWhiteSpace()) return null;
return decimal.Parse(decimalString);
}
Run Code Online (Sandbox Code Playgroud)