C #InNullableType(Translation)
This isC #2.0For more information about the new features of the language, seeC # Language spec.NullableType is used to assign a simple value type objectNullValue or an unknown value. This is common in database operations. Of course, it will also be applied elsewhere.
In the past, we could also fulfill our needs through other means:
1.Use a boxing type. In this way, we cannot use a strong type, and we also need to use a heap to arrange each type.
2.Package the value typeClass. This is a strong type, but heap is also used. At the same time, you must write such a package class.
3.Package into a struct and provide support for null assignment. This is a good solution, but you have to write it yourself.
To make it easier to useVs2005, We will introduce a new type named"Nullable", As follows:
(In fact, it is much more complicated than the following example, but we start with a simple example)
Struct Nullable<T> { Public BoolHasvalue; PublicT value; } |
You can use this struct directly. We have added someNullableSyntax to make the resultCodeMore clearly, the entry syntax is as follows:
Nullable<Int> X =New Nullable<Int> (125 ); |
I can also write:
It looks simple. Similarly, you need to write a small test to describe the usage as follows:
You can write the empty statement in this way.
Finally, we can write expressions more easily.
If you wantIntType objects are added up, and theirNullValue. If I do not have language support, I may need to write it like this:
Nullable<Int> X =New Nullable<Int> (125 ); Nullable<Int> Y =New Nullable<Int> (33 ); Nullable<Int> Z = (X. hasvalue & Y. hasvalue )? New Nullable<Int> (X. Value + Y. Value ):Nullable<Int>. Nullvalue; |
At least I think I have to write it like this--It's too complicated. I cannot guarantee that this code can work properly.
If onlyNullableThe compiler does not provide enough support, and the above writing is really ugly.
Of course, the compiler supports it. You can write it like this:
Int? X = 125; Int? Y = 33; Int? Z = x + y; |
Source:
Http://blogs.msdn.com/ericgu/archive/2004/05/27/143221.aspx
MsdnRelatedArticle:
MS-help: // Ms. VSCC. v80/ms. msdn. v80/ms. netdevfx. Ven en/cpref2/html/t_system_nullable.htm