. NET can be null type [Nullable & lt; T & gt;] implementation principle,. netnullable

Source: Internet
Author: User

. NET can be null type [Nullable <T>] implementation principle,. netnullable

To enable the value type in. Net to be assigned null, Microsoft has added the Nullable <T> type, which can also be abbreviated as T ?. But Nullable <T> itself is a struct and a value type. How does it assign null values to the value type?

The following describes how Nullable <T> is implemented by customizing a null value type.

Custom Value Type

Struct XfhNullable <T> where T: struct {private T innerValue; // This attribute is very important public bool HasValue {set; get;} public T Value {get {return HasValue? InnerValue: throw new InvalidOperationException () ;}} public XfhNullable (T value) {this. innerValue = value; HasValue = true;} public T GetValueOrDefault (T value) {return HasValue? This. innerValue: value;} public T GetValueOrDefault () {return this. innerValue ;}}

The general function of a struct with a null value type has been defined. Let's create an instance with a null value type to verify it.

Using static System. console; class Program {static void Main () {// use the struct default no-argument constructor to instantiate XfhNullable <int> num = new XfhNullable <int> (); writeLine (num. hasValue); WriteLine (null_num.GetValueOrDefault ());}}

As you can see, the variable num does not contain values. If you call GetValueOrDefault (), the default value 0 is obtained;

When null is assigned to the variable num, the compiler reports the error Cannot convert null to 'xfhnullable <int> 'because it is a non-nullable value type. This is because the compiler has defined the struct XfhNullable. <T> it is considered as a normal value type rather than a null value type, therefore, we also need to add the conversion function between the null type and XfhNullable <T>.

public static implicit operator XfhNullable<T>(T? nullabelValue){  if (nullabelValue== null)  {    return new XfhNullable<T>();  }  return new XfhNullable<T>(nullabelValue.Value);}

The code above implements implicit conversion of the null value type to XfhNullable <T>. After adding the code above, it is found that the compiler no longer reports an error. XfhNullable <T> has become a null value type.

static void Main(){  XfhNullable<int> null_num = null;  WriteLine(null_num.HasValue);}

The attribute HasValue in XfhNullable <T> is used to mark whether the current type is null. If so, False is returned; otherwise, True is returned. If the Value attribute of this type is called when the HasValue is False, an InvalidOperationException is thrown. However, you can call the GetValueOrDefault () method to obtain the default value of the type.

The Nullable <T> type can be determined by the operator = to determine whether the value is null. We can also use the operator overload to implement this function:

public static bool operator ==(XfhNullable<T> cn, object obj){  if (cn.HasValue)  {    return false;  }  return true;}public static bool operator !=(XfhNullable<T> cn, object obj){  return !(cn == obj);}
static void Main(){  XfhNullable<int> null_num = null;  WriteLine(null_num == null);}

Next, we will implement the conversion between the common value type and XfhNullable <T>:

public static implicit operator XfhNullable<T>(T value){  return new XfhNullable<T>(value);}public static explicit operator T(XfhNullable<T> value){  return value.innerValue;}
Static void Main () {XfhNullable <int> null_num = null; null_num = 12; // implicit conversion of the int type to XfhNullable <int> type WriteLine (null_num = null ); writeLine (null_num.Value); int I = (int) null_num; // XfhNullable <int> type forced conversion to int type WriteLine (I );}

Obtain the instance type at run time:

static void Main(){  XfhNullable<int> null_num = 12;  WriteLine(null_num.GetType());}

The returned value is not very friendly. We hope to return the built-in value type, System. Int32. The specific implementation code is as follows:

// Because the GetType method in the Object class does not allow subclass rewriting (avoid subclass hiding its actual type) // use the new keyword to hide the GetType method public new Type GetType () {return innerValue in the Object class. getType ();}

Conclusion: no empty value type is available.

So far, we have customized a value type XfhNullable that can be empty <T>. Through the above code, we can easily find that the so-called value type that can be empty does not exist, it uses the HasValue attribute to mark the null value. Internally, it maintains the value of this type through the innerValue field (which corresponds to the value field in Nullable <T>, if the value is null, innerValue is initialized as the initial value of the value type. In other words,Nullable <T> only logically assigns null values to the value type, giving us the feeling that the value type can be null.

Finally, we can deploy and Unbox empty values.

When executing the packing operation on the Nullable <T> instance, CLR first checks whether it is null. If so, CLR returns null without packing anything; if the Instance Value is not null, the Instance Value (Value Attribute) is obtained and the Value is boxed.

If it is null,Nullable <T> ()Instance. For a specific value, such as 5, returnNullable <T> (5)Instance.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.