簡體   English   中英

將 c# 空合並運算符與 int 一起使用

[英]Use c# Null-Coalescing Operator with an int

我正在嘗試在 int 上使用 null 合並運算符。 當我在字符串上使用它時它可以工作

UserProfile.Name = dr["Name"].ToString()??"";

當我嘗試在這樣的 int 上使用它時

UserProfile.BoardID = Convert.ToInt32(dr["BoardID"])??default(int);

我收到此錯誤消息

操作員 '??' 不能應用於“int”和“int”類型的操作數

我發現這篇博客文章使用了 http://davidhayden.com/blog/dave/archive/2006/07/05/NullCoalescingOperator.aspx和 int 數據類型。 誰能告訴我做錯了什么?

我懷疑如果 dr["BoardID"] 是數據庫中的 NULL ,您真正想做的是將 BoardID 設置為 0 。 因為如果 dr["BoardID"] IS null,Convert.ToInt32 將失敗。 嘗試這個:

UserProfile.BoardID = (dr["BoardID"] is DbNull) ? 0 : Convert.ToInt32(dr["BoardID"]);

是的,當然......因為int不能是 null。
它只有 32 位,所有組合都代表一個有效的 integer。

使用int? 相反,如果你想要可空性。 (它是System.Nullable<int>的簡寫。)

一個int永遠不是null ,所以應用?? 對此毫無意義。

實現您想要的一種方法是TryParse

int i;
if(!int.TryParse(s, out i))
{
    i = 0;
}

或者因為你想得到0default(int)你可以扔掉 if,因為在錯誤情況下TryParse的 output 參數已經是default(int)

int i;
int.TryParse(s, out i);

您鏈接的文章左側沒有int ?? 但是int? . 這是Nullable<int>的快捷方式,因此支持null ?? 有道理。

int? count = null;    
int amount = count ?? default(int); //count is `int?` here and can be null

在你的鏈接?? 運算符應用於可以具有 null 值的Nullable<int> ( int? )。

Null-coalescing 運算符的工作方式如下:

如果運算符左側的值為 null 則返回運算符右側的值。 Int 是值類型,因此它永遠不會有 null 值。 這就是你得到錯誤的原因。

在示例中,您將線條與?? int上的運算符是:

int? count = null;

int amount = count ?? default(int);

因此在該示例中 int 可以為空

您只能對引用類型或可為空的值類型使用 null 合並運算符。 例如: string ,還是int? 請參閱http://msdn.microsoft.com/en-us/library/ms173224.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM