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

时间:2009-11-10 01:25:40

标签: c# nullable

我的代码与此类似:

public xyz (int? a)
{
  if (a.HasValue)
  { 
    // here DoSomething has parameters like DoSomething(int x)
    blah = DoSomething(a);

我收到错误(无法从int转换为int)。有没有办法可以将变量'a'传递给我的函数,而不必执行DoSomething(int? x)

2 个答案:

答案 0 :(得分:16)

使用可变量变量的Value属性:

public xyz (int? a) {
  if (a.HasValue) { 
    blah = DoSomething(a.Value);
    ...

GetValueOrDefault方法在某些情况下也可能有用:

x = a.GetValueOrDefault(42);  // returns 42 for null

y = a.GetValueOrDefault(); // returns 0 for null

答案 1 :(得分:6)

您可以将int?投射到int或使用a.Value

if (a.HasValue)
{ 
  blah = DoSomething((int)a);

  // or without a cast as others noted:
  blah = DoSomething(a.Value);
}

如果接下来是传入默认值的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 */));