欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談C# 中的可空值類型 null

 更新時(shí)間:2013年12月02日 15:47:53   作者:  
這篇文章主要介紹了C# 中的可空值類型 null,有需要的朋友可以參考一下

C# 不允許把 null 賦給一個(gè)值類型的數(shù)據(jù)。在 C# 中,以下語句是非法的:

復(fù)制代碼 代碼如下:

int a = null;    // 非法 

但是,利用 C# 定義的一個(gè)修飾符,可將一個(gè)變量聲明為一個(gè)可空(nullable)值類型。可空值類型在行為上與普通值類型相似,但可以將一個(gè) null 值賦給它。如下所示:

復(fù)制代碼 代碼如下:

int? a = null;      // 合法

當(dāng)把一個(gè)變量定義為可空值類型時(shí),該變量依然可以被賦值為 0,代碼如下所示:

復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 可空類型
{
    class Program
    {
        static void Main(string[] args)
        {
            int? a = null;

            Console.WriteLine("a = {0}", a);
            a = 0;
            Console.WriteLine("a = {0}", a);
        }
    }
}

運(yùn)行結(jié)果為:

可空類型有如下屬性:

復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int? i = null;
            if (!i.HasValue)    // 若 i 包含一個(gè)真正的值,則 i.HasValue 為true
            {
                i = 99;
            }
            Console.WriteLine(i.Value); // i 的值
        }
    }
}

// i.HasValue 比 i != null 走了不少冤枉路,i.Value 也比 i 更麻煩
// 但是當(dāng)使用更加復(fù)雜的值類型(struct)來聲明可空類型時(shí), .HasValue 和 .Value 就有了優(yōu)勢

相關(guān)文章

最新評論