2010-06-14 48 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