好象有面向對象編程語言以來,對于基礎類型數據,如int、float等,不支持為其賦值為null,我們為了將其表示為null,通常是賦予一個特定的值,如int則賦值為-1。現在在c#2.0中有一個很好的解決方法:就是使用基礎類型+?,比如int?,float?,
下面是msdn的相關文章:
ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_csref/html/088b1f0d-c1af-4fe1-b4b8-196fd5ea9132.htm
如果 ?? 運算符的左操作數非空,該運算符將返回左操作數,否則返回右操作數。
備注
可空類型可以包含值,或者可以是未定義的。?? 運算符定義當可空類型分配給非可空類型時返回的默認值。如果在將可空類型分配給非可空類型時不使用 ?? 運算符,將生成編譯時錯誤。如果使用強制轉換,并且當前未定義可空類型,將發生 InvalidOperationException 異常。
有關更多信息,請參見 可為空的類型(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");
}
}
|
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

