Nullable and Its Usage of explicit and implicit. nullableimplicit
Question 1: Nullable <T> can be assigned null.
First look at two lines of C # code
int? i1 = null; int? i2 = new int?();
Int? That is, Nullable <int>, just as int Is In Int32;
Nullable <T> is a very special structure type. It can be assigned null values (so I thought it was a reference type), which is essentially equivalent to new;
Through debugging, we can find that the above two values are both null, but in fact we can call some of their attribute methods, such as "HasValue". It can be seen that "= null" is just a blind eye;
If their "Value" attribute is called, an "InvalidOperationException" exception is thrown. Note that the exception is not a null reference exception. The exception information is "Other information: NULL objects must have a Value .";
We recommend that you use the "GetValueOrDefault" method to obtain the Value of this type, instead of determining the HasValue and then removing the Value;
We recommend that you do not use the "= null" logical judgment. The HasValue attribute should be used.
Question 2: Nullable <T> can be assigned to the T type.
Still look at two lines of C # code
int? iNull = 2; int i = (int)iNull;
Very common code, but each line of code contains the type, "int ?" Implicit conversion and display conversion between int and Nullable. Nullable <T> provides two methods to convert Null Types:
public static explicit operator T(Nullable<T> value); public static implicit operator Nullable<T>(T value);
Operator is an operator overload, so the two products can also be considered as an operator overload of "=". explicit supports display conversion, and implicit supports implicit conversion, using the following:
Class UserInfo {public int ID {get; set;} public string Name {get; set;} public static explicit operator UserInfo (int id) {Console. writeLine ("Get User object whose User id is [{0}]", ID); return new UserInfo {id = id};} public static implicit operator UserInfo (string name) {Console. writeLine ("Get the User object whose username is [{0}]", name); return new UserInfo {Name = name };}}
Call:
UserInfo user1 = (UserInfo)2; UserInfo user2 = "bajie";