2010-06-14 131 views
7

我已经创建了一个保存对象并返回保存的新对象的ID的SPROC。现在,我想返回一个int而不是int吗?如何转换int? into 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? 
} 

感谢您的帮助

回答

16
return id.Value; // If you are sure "id" will never be null 

return id ?? 0; // Returns 0 if id is null 
+1

请注意,id.Value会在id为null时抛出异常。在某些情况下,这将是适当的,否则,使用'??'。 – 2010-06-14 19:19:55

+0

这不是我所建议的吗? – 2010-06-14 19:20:45

+0

'''只能使用Nullable <>,还是常规引用类型?如果适用于所有参考类型,则为 – 2010-06-14 19:21:23

3
return id.Value; 

您可能要检查是否id.HasValue是真实的,并返回0或东西,如果没有。

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

或**返回ID ?? 0 **。完全一样:) – 2010-06-14 19:23:25

+1

这是一个相当冗长的方式说''ID ?? 0'“ – Blorgbeard 2010-06-14 19:23:49

+0

@Blogbeard:从技术上讲,这将是'返回ID? 0;':) – 2010-06-14 19:25:24

6

您可以在Nullable上使用GetValueOrDefault()函数。

return id.GetValueOrDefault(0); // Or whatever default value is wise to use... 

注意,这类似于coalescing answer by Richard77但我会稍微更可读的说...

然而,在决定是否这是一个好主意是你。这样或许是一个例外更合适?

if (! id.HasValue) 
    throw new Exception("Value not found"); // TODO: Use better exception type! 

return id.Value; 
+1

+1,因为它暗示抛出异常可能是合适的。在我看来,过多的程序员很快就会使用默认值,而没有首先确保null不是真的是错误。 – Phong 2010-06-15 00:27:51

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

这将返回的ID的情况下,在另一种情况下的值不为空和0。

+0

'return id ??怎么回事? 0;',它完全一样,更有效率? – 2010-06-15 10:21:37