[Preparing for the interview] IV. Empty Nullable & lt; T & gt; what is nullable?

Source: Internet
Author: User

[Preparing for the interview] IV. Empty Nullable <T> what is nullable?
Why cannot I leave the Value Type Empty?

First, we all know that the default values of the reference type are null, and the default values of the value type are non-null.

Why can the reference type be empty? Because the reference type variables store the address reference of an object (just like a url corresponds to a page ), when the reference type value is null, the variable value points to an empty reference (like an empty url)

Why can't there be null values? In fact, it is very simple, because for example, the int value range is-2147483648 to 2147483647. There is no such position for the null value at all.

Why do we need to use a void type?

For example, we define a Person, which has three attributes: BeginTime, EndTime, and Age ).

If this person is still alive, how can I assign a value to the date of death? Someone is clever enough to say "it's empty ". Yes, this is our requirement.

When Microsoft introduced the System. Nullable (T>) type to C #2.0, the Person class is defined below.

1 public class Person 2 {3 /// <summary> 4 /// Date of birth 5 /// </summary> 6 public DateTime BeginTime {get; set ;} 7 /// <summary> 8 /// date of death 9 /// </summary> 10 public System. nullable <DateTime> EndTiem {get; set;} 11 public int Age12 {13 get14 {15 if (EndTiem. hasValue) // if it fails (if it has a value, it indicates it is dead) 16 {17 return (EndTiem. value-BeginTime ). days; 18} 19 else // 20 {21 return (DateTime. now-BeginTime ). days; 22} 23} 24} 25}

 

In this way, we can easily get a person's age.

Static void Main (string [] args) {Person p1 = new Person () {BeginTime = DateTime. parse ("1990-07-19")}; Person p2 = new Person () {BeginTime = DateTime. parse ("1893-12-26"), EndTiem = DateTime. parse ("1976-09-09")}; Console. writeLine ("I am" + p1.Age + "years old. "); Console. WriteLine (" Grandpa Mao lives "+ p2.Age +" years old. "); Console. ReadKey ();}
Implementation of the null type

We used System. Nullable <DateTime> to indicate the time type that can be empty. In fact, we usually use DateTime? Add a question mark directly after type T. The two are equivalent. Thanks to Microsoft's syntactic sugar.

Let's see what System. Nullable <T> is.

The search operator is a structure. We also see the HasValue and Value attributes of our properties. It turned out to be so simple. Two properties of a structure, one storage value, and one storage value. Next let's try it.

Sorry, we are disappointed. As we mentioned earlier, the value type cannot be null (the structure is also a value type ).

What should I do! What should I do! No, Microsoft also defines its own structure. How can it assign null values directly. (Strange, strange. After all, Microsoft may have gotten special treatment)

But does this stop us? NO! We all know that when we look at Microsoft's IL (intermediate language), it's like taking off its clothes. We can see what we don't understand in many cases, next we will take off our clothes.

First, we use several different methods to assign values to the null type.

static void Main(string[] args){    System.Nullable<int> number1 = null;    System.Nullable<int> number2 = new System.Nullable<int>();    System.Nullable<int> number3 = 23;    System.Nullable<int> number4 = new System.Nullable<int>(88);    Console.ReadKey();}    

 

Then use reflector to check the compiled IL.

Originally, the value assignment of the null type is directly equivalent to constructing an instance. When null is assigned, an empty constructor is called. When a value exists, the constructor with parameters is passed in. (The village is different. In this case, can we continue to simulate the null type with MyNullable <T> in the preceding example? And continue reading .)

Public struct MyNullable <T> where T: struct {// Error 1 structure cannot contain an explicit non-parameter constructor // fortunately, the default bool value is false, so this is not displayed here. _ hasValue = false does not affect // public MyNullable () // {// this. _ hasValue = false; //} public MyNullable (T value) // constructor with parameters {this. _ hasValue = true; this. _ value = value;} private bool _ hasValue; public bool HasValue // whether it is not empty {get {return _ hasValue;} private T _ value; public T Value // Value {get {if (! This. _ hasValue) // if there is no value, an Exception will be thrown when access is made. {throw new Exception ("an object that can be empty must have a value") ;}return _ value ;}}}

 

XI, which has basically been simulated as an empty type. (However, we still cannot assign values directly. We can only use the custom void type through the constructor ).

The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace can be empty type {public class Person {// <summary> /// Date of Birth /// </summary> public DateTime BeginTime {get; set ;} /// <summary >/// date of death /// </summary> public MyNullable <DateTime> EndTiem {get; set ;} // here, use MyNullable /// <summary> // Age // </summary> public double Age {get {if (End Tiem. hasValue) // if it fails (if it has a value, it indicates it is dead) {return (EndTiem. value-BeginTime ). days/365;} else // {return (DateTime. now-BeginTime ). days/365 ;}}} public struct MyNullable <T> where T: struct {// Error 1 The structure cannot contain an explicit non-parameter constructor // fortunately, the default bool value is false, so this is not displayed here. _ hasValue = false does not affect // public MyNullable () // {// this. _ hasValue = false; //} public MyNullable (T value) // constructor with parameters {this. _ hasValue = true; this. _ Value = value;} private bool _ hasValue; public bool HasValue // whether it is not empty {get {return _ hasValue;} private T _ value; public T Value // Value {get {if (! This. _ hasValue) // if there is no value, an Exception will be thrown when access is made. {throw new Exception ("an object that can be empty must have a value") ;}return _ value ;}}} class Program {static void Main (string [] args) {Person p1 = new Person () {BeginTime = DateTime. parse ("1990-07-19")}; Person p2 = new Person () {BeginTime = DateTime. parse ("1893-12-26"), EndTiem = new MyNullable <DateTime> (DateTime. parse ("1976-09-09") // use the parameter constructor of MyNullable here}; Console. writeLine ("My this year" + P1.Age + "years old. "); Console. WriteLine (" Grandpa Mao lives "+ p2.Age +" years old. "); Console. ReadKey ();}}}View Code

 

And the system can be empty type to get the same result.

Summary
  • The null type is the structure (that is, the value type)
  • Therefore, the null value of the null type is different from the null value of the reference type. (The null type does not reference the null type, but uses another representation of the structure to represent null)

 

Some people asked, How can we assign values directly? There is no good way to do this either. Maybe the support of the compiler is needed.

The above content is all nonsense. I hope it will be of little use to you. Thank you for reading this article.

(Starter link: http://www.cnblogs.com/zhaopei/p/5537759.html)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.