//通俗讲,就是查看对象是否有值
获取一个值,指示当前的 Nullable 对象是否有值。
//hasvalue是返回值为bool的属性,而非方法
属性值
如果当前的 Nullable 对象具有值,则为 true;如果当前的 Nullable 对象没有值,则为 false。如果 HasValue 属性为 true,则可以使用 Value 属性访问当前 Nullable 对象的值。
//官方关于nullable类的hasvalue属性的示例
using System; class Sample { public static void Main() {
//声明变量 datatime类型的变量mynow,注:此时未初始化仅声明
DateTime? myNow; // Assign the current date and time to myNow then display its value.
//初始化变量mynow,以datatime.now
myNow = DateTime.Now;
//调用display方法显示mynow变量的值
Display(myNow, "1) "); // Assign null (Nothing in Visual Basic) to myNow then display its value.
//mynow重置为null,可理解为没有提供值
myNow = null; Display(myNow, "2) "); } // Display the date and time.
//display方法的定义体如下
//方法参数为displaydatatime及title
public static void Display(DateTime? displayDateTime, string title) { // If a value is defined for the displayDatetime argument, display its value; otherwise, // display that no value is defined. Console.Write(title);
//通过nullable对象的hasvalue属性判断方法display 的参数displaydatatime
//是否传入值,若传入值则为true,否则为false
if (displayDateTime.HasValue == true)
//表明displaydatatime有值,显示下述内容
Console.WriteLine("The date and time is {0:F}.", displayDateTime.Value); else Console.WriteLine("The date and time is not defined."); } }
//示例代码的输出 /* This code example produces the following results: 1) The date and time is Tuesday, April 19, 2005 4:16:06 PM. 2) The date and time is not defined. */
