天天看點

可空值類型

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.SqlClient;

namespace _03可空值類型

{

class Program

{

static void Main(string[] args)

{

#region 可空值類型

//引用類型可空,值類型不可空

//int n = 10;

//string s = "hello";

//s = null;

//n = null;

// int? 等價于 Nullable<int>

//int? n = 10;

//Nullable<int> n = 10;

//n = 100;

//n++;

//Console.WriteLine(n);

//Console.WriteLine("ok");

//Console.ReadKey();

//Nullable繼承于Struct,結構體是值類型的,并不能真正指派為null(詳見圖一)

//是以可控制類型并沒有把一個NULL值指派給 變量n,而是編譯時用另一中方式讓你看起來可以為NULL。

//内部執行過程

//Nullable<int> n;

// 如果有值,那麼内部HasValue屬性指派為true

//n.HasValue = true;

//然後指派

//n.Value = 10;

//Nullable<int> n = null;

//如果為Null,那麼隻把HasValue屬性指派為false,并不真正指派。

//n.HasValue = false;

// 使用到的時候,例如判斷 int? n =null 時候為null值。

//if (n==null) //實際等價于 if(!n.HasValue)

//{

//}

// 下同

//double? d = 10.1;

//float? x = 99;

//bool? b = false;

////string? s = "aaa"; 報錯可空值類型隻能用于值類型,不能應用于引用類型,因為引用類型本身可以指派為null。

#endregion

#region 使用帶參數sql語句時的一個問題

string sql = "insert into TblPerson values(@name,@age,@height,@gender)";

SqlParameter[] pms = new SqlParameter[] {

new SqlParameter("@name","王五"),

new SqlParameter("@age",0), //報錯 重載識别錯誤,詳見圖二。

//new SqlParameter("@age",System.Data.SqlDbType.Int){Value=0}, //建議指明類型。

new SqlParameter("@height",180),

new SqlParameter("@gender",true)

};

_02封裝SqlHelper類.SqlHelper.ExecuteNonQuery(sql, pms);

Console.WriteLine("ok");

Console.ReadKey();

}

}

}

圖一 、利用反編譯軟體 .NetReflector 7.0 檢視内部代碼:

可空值類型

 圖二 重載問題

樹立目标,保持活力,gogogo!