C # 中的“ int”和“ int”有什么区别?

我有90% 的把握以前在 stackoverflow 上看到过这个答案,事实上我从来没有看到过“ int?”但是不管我怎么搜索,我都找不到之前的帖子,这让我很抓狂。

有可能是我不小心吃了有趣的蘑菇,但如果不是的话,有没有人能指出之前的帖子,如果他们能找到或者重新解释一下?我的堆栈溢出搜索-fu 显然是太低了... 。

126848 次浏览

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

int? is the same thing as Nullable. It allows you to have "null" values in your int.

int belongs to System.ValueType and cannot have null as a value. When dealing with databases or other types where the elements can have a null value, it might be useful to check if the element is null. That is when int? comes into play. int? is a nullable type which can have values ranging from -2147483648 to 2147483648 and null.

Reference: https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

the symbol ? after the int means that it can be nullable.

The ? symbol is usually used in situations whereby the variable can accept a null or an integer or alternatively, return an integer or null.

Hope the context of usage helps. In this way you are not restricted to solely dealing with integers.

you can use it when you expect a null value in your integer especially when you use CASTING ex:

x= (int)y;

if y = null then you will have an error. you have to use:

x = (int?)y;

Int cannot accept null but if developer are using int? then you store null in int like int i = null; // not accept int? i = null; // its working mostly use for pagination in MVC Pagelist