如何将int?转换为int

7

我创建了一个存储对象并返回新存储对象id的SPROC。现在,我想要返回int而不是int?

public int Save(Contact contact)
{
  int? id;
  context.Save_And_SendBackID(contact.FirstName, contact.LastName, ref id);
  //How do I return an int instead of an int?
}

感谢您的帮助。
5个回答

16
return id.Value; // If you are sure "id" will never be null
或者
return id ?? 0; // Returns 0 if id is null

1
请注意,当id为null时,id.Value将抛出异常。在某些情况下,这可能是适当的,否则,请使用?? - Eric Mickelsen
?? 只能用于 Nullable<> 类型,还是普通的引用类型也可以使用? - Nelson Rothermel
2
如果适用于所有引用类型,则 x ?? y 基本上是 x!=null ? x : y 的简写形式。 - SWeko
太好了,谢谢。我知道它的作用,只是突然想到这个问题。 - Nelson Rothermel

6
您可以在 Nullable 上使用 GetValueOrDefault() 函数。
return id.GetValueOrDefault(0); // Or whatever default value is wise to use...

请注意,这与Richard77的合并答案类似,但我认为稍微更易读一些...
然而,决定是否采用此方法取决于您。也许使用异常更为适当?
if (! id.HasValue)
    throw new Exception("Value not found"); // TODO: Use better exception type!

return id.Value;

1
+1 建议抛出异常可能是适当的做法。在我看来,太多程序员很快就使用默认值,而没有先确保 null 确实不是一个错误。 - user315772

3
return id.Value;

你可能需要检查id.HasValue是否为true,如果不是,则返回0或其他内容。

0
if (id.HasValue) return id.Value;
else return 0;

1
返回已翻译的文本:或return id??0。完全一样 :) - Philippe Leybaert
1
这是一种比较冗长的表达方式,意思等同于 "id ?? 0"。 - Blorgbeard
@Blogbeard:从技术上讲,应该是 return id ?? 0; :) - Nelson Rothermel
@Philippe - 实际上,它并不完全相同;按照书写方式检查值时会检查两次是否已分配值。??方法只检查一次。要检查零次(并且仍然表现完全相同),您可以使用return id.GetValueOrDefault() - Marc Gravell

0
return id.HasValue ? id.Value : 0;

如果id不为null,则返回其值,否则返回0。


return id ?? 0;有什么问题?它实现了完全相同的功能并且更加高效。 - Philippe Leybaert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接