我不明白为什么这不起作用
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: null;
Run Code Online (Sandbox Code Playgroud)
slu*_*ter 47
因为null
是类型object
(有效无类型),您需要将其分配给类型化对象.
这应该工作:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: (decimal?)null;
Run Code Online (Sandbox Code Playgroud)
或者这更好一点:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: default(decimal?);
Run Code Online (Sandbox Code Playgroud)
以下是默认关键字的MSDN链接.
不要用decimal.Parse
.
Convert.ToDecimal
如果给出一个空字符串,则返回0.decimal.Parse
如果要解析的字符串为null,则抛出ArgumentNullException.
试试这个:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ?
decimal.Parse(txtLineCompRetAmt.Text.Replace(",", "")) :
(decimal?) null;
Run Code Online (Sandbox Code Playgroud)
问题是编译器不知道null
具有什么类型.所以你可以把它投到decimal?