C# – 基本问题:什么是’?’?
我在想什么?
在C#意味着什么?
我看到的东西是: DateTime?
还是int?
。 我想这是特定于C#4.0的?
我不能在谷歌找它,因为我不知道这个东西的名字。
问题是我正在使用DateTime并且我有很多DateTime
转换错误(从DateTime
到DateTime?
)。
谢谢
它是编写Nullable
或Nullable
的简写。 Nullables与值类型一起使用,不能为null(它们总是有值)。
顺便说一下,它不是特定于C#4的。
你只能指定一个int?
如果它有值,则为int
,因此您的代码必须执行以下操作:
int? n = 1; int i = n ?? default(int); //or whatever makes sense
另请注意, Nullable
有两个属性, HasValue
和Value
,如果已设置Value
,则可以使用test并获取实际值。
这意味着它是一个可以为空的类型 。
它允许您为值类型(如int和DateTime)分配空值。 它对数据库中的可选字段等内容非常有帮助。
它指定可空类型 。
我想这是C#4.0专用的C#?
自2.0以来它一直在C#中
的?
是一个可以为null的值类型。
你可以用??
运算符将其与值类型混合:
const int DefaultValue = -1; // get a result that may be an integer, or may be null int? myval = GetOptionalIdFromDB(); // the value after ?? is used if myval is null int nonNullable = myval ?? DefaultValue;
可以将可空类型与null进行比较,因此以上是以下内容的简写:
if( myval != null ) { nonNullable = myval.Value; } else { nonNullable = DefaultValue; }
但我更喜欢??
需要注意的是:[编辑:显然这有时只会发生]
// nullable type properties may not initialize as null private int? foo; // foo = 0 // to be certain, tell them to be null private int? foo = null;
它是声明generics类Nullable
的实现的简写方式,其中T是不可为空的值类型。
所以
int? i = null;
是相同的
Nullable i = null;
如上所述, Nullable
公开HasValue属性,因此您可以在处理之前检查i
是否有值。
有趣的是:如果你施放Nullable
对于一个对象,你可以强制转换为int或Nullable
因为它在装箱前有一个值。 但是,如果你施放Nullable
对于一个对象,当你转换回一个int时你会得到一个NullReferenceException但你可以强制转换为Nullable
。
正如其他人所说,在类型名称之后,它意味着可以为空的类型。
? 也用于条件运算符。
int max = x > y ? x : y
这相当于:
int max; if( x > y ) { max = x; } else { max = y; }