1,Bool? And bool(In vs2012)
The bool keyword isSystem. BooleanAlias(In fact, bool is the basic value type, Boolean is the object, bool is in C #, and Boolean is in. NET Framework. Actually, they are the same. There is no difference)Used to generate a variable to store Boolean values true and false. Bool Data Types in memory1Bytes. But bool? It can be a null type.(The following extensions are explained)Contains three different values: True, false, and null. The default value of the bool variable isFalseAnd bool? The default value of the variable isNull. So bool? Type cannot be used in conditional statements (such as if, for, or while). Otherwise, a compiler error occurs.
For example:
Bool? B =Null;If(B ){}
AppealCodeIs not allowed, because the meaning of null in the context of the condition is not clear. To use bool? In the condition statement ?, DetermineHasvalueNot null, and then forcibly convert itBool; If the bool of a null value is used? If a forced conversion is executedInvalidoperationexceptionException.
Therefore, Microsoft provides the following methods:Convert bool? Forced conversion of security to bool (this is the key)
bool ? Test = null ;... If (! Test. hasvalue) /// select a value {test = isinitialized () ;} If ( bool ) Test ){...}
note : In C ++, bool values can be converted to int values, that is, false is equivalent to zero, while true is equivalent to a non-zero value. But in C #, the does not exist bool type and other types are converted to each other.
2. Extension: use a type that can be null in C #
(1) there are two types of declarations that can be null:
system. nullable variable or t? Variable
T is the basic type that can be null , t can be any value type including struct, but cannot be a reference type. Actually, T? indicates a value in the T range + that can be null.
(2) type example
any value type can be used as a basis for null types, such:
int ? I = 10 ; double ? D1 = 3.14 ; bool ? Flag = null ; char ? Letter = ' A ' ; int ? [] Arr = New int ? [ 10 ];
######Bool, String, int are called value types; Boolean, String, int32 are called reference types ). The value type has memory.Stack)And the reference type exists.Heap).
(3) member
Each instance of a type that can be null has two public read-only attributes:
Hasvalue
Hasvalue belongs to the bool type. When a variable contains a non-null value, it is set to true.
Value
The value type is the same as the basic type. If hasvalue is true, it indicates that value contains a meaningful value. If hasvalue is falseInvalidoperationexceptionException.
-- Postscript: as mentioned by the teacher in the class, I checked it on csdn and other websites and summarized it ,@_@