好象有面向?qū)ο缶幊陶Z(yǔ)言以來(lái),對(duì)于基礎(chǔ)類(lèi)型數(shù)據(jù),如int、float等,不支持為其賦值為null,我們?yōu)榱藢⑵浔硎緸閚ull,通常是賦予一個(gè)特定的值,如int則賦值為-1。現(xiàn)在在c#2.0中有一個(gè)很好的解決方法:就是使用基礎(chǔ)類(lèi)型+?,比如int?,float?,
下面是msdn的相關(guān)文章:
ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_csref/html/088b1f0d-c1af-4fe1-b4b8-196fd5ea9132.htm
如果 ?? 運(yùn)算符的左操作數(shù)非空,該運(yùn)算符將返回左操作數(shù),否則返回右操作數(shù)。
備注
可空類(lèi)型可以包含值,或者可以是未定義的。?? 運(yùn)算符定義當(dāng)可空類(lèi)型分配給非可空類(lèi)型時(shí)返回的默認(rèn)值。如果在將可空類(lèi)型分配給非可空類(lèi)型時(shí)不使用 ?? 運(yùn)算符,將生成編譯時(shí)錯(cuò)誤。如果使用強(qiáng)制轉(zhuǎn)換,并且當(dāng)前未定義可空類(lèi)型,將發(fā)生 InvalidOperationException 異常。
有關(guān)更多信息,請(qǐng)參見(jiàn) 可為空的類(lèi)型(C# 編程指南) 。
示例
// nullable_type_operator.cs using System; class MainClass { static int? GetNullableInt() { return null; } static string GetStringValue() { return null; } static void Main() { // ?? operator example. int? x = null; // y = x, unless x is null, in which case y = -1. int y = x ?? -1; // Assign i to return value of method, unless // return value is null, in which case assign // default value of int to i. int i = GetNullableInt() ?? default(int); string s = GetStringValue(); // ?? also works with reference types. // Display contents of s, unless s is null, // in which case display "Unspecified". Console.WriteLine(s ?? "Unspecified"); } } |
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
