我有与此类似的代码:
public xyz (int? a)
{
if (a.HasValue)
{
// here DoSomething has parameters like DoSomething(int x)
blah = DoSomething(a);
Run Code Online (Sandbox Code Playgroud)
我收到错误(无法从int?转换为int).有没有办法我可以将变量'a'传递给我的函数而不必这样做DoSomething(int? x)?
Guf*_*ffa 16
使用Value可空变量的属性:
public xyz (int? a) {
if (a.HasValue) {
blah = DoSomething(a.Value);
...
Run Code Online (Sandbox Code Playgroud)
GetValueOrDefault在某些情况下,该方法可能也很有用:
x = a.GetValueOrDefault(42); // returns 42 for null
Run Code Online (Sandbox Code Playgroud)
要么
y = a.GetValueOrDefault(); // returns 0 for null
Run Code Online (Sandbox Code Playgroud)
您可以将其int?转换为int或使用a.Value:
if (a.HasValue)
{
blah = DoSomething((int)a);
// or without a cast as others noted:
blah = DoSomething(a.Value);
}
Run Code Online (Sandbox Code Playgroud)
如果这后面跟着一个传递默认值的else,你也可以在一行中处理所有这些:
// using coalesce
blah = DoSomething(a?? 0 /* default value */);
// or using ternary
blah = DoSomething(a.HasValue? a.Value : 0 /* default value */);
// or (thanks @Guffa)
blah = DoSomething(a.GetValueOrDefault(/* optional default val */));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3329 次 |
| 最近记录: |