C#:将可空变量传递给只接受非空变量的方法

Ted*_*ddy 6 c# nullable

我有与此类似的代码:

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)


Mic*_*ren 6

您可以将其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)

  • @Guffa:非常主观.对于知道该语言的人来说,GetValueOrDefault是详细的,并且合并就像它得到的一样清晰.同意铸造部分. (2认同)