C# - 基本问题:什么是“?”? [英] C# - Basic question: What is '?'?
问题描述
我不知道什么?
意味着在C#?
我看到喜欢的东西:的DateTime
或 INT
?。我想这是专门针对C#4.0?
我不能看着它在谷歌,因为我不知道这个东西的名字。
问题是我使用的日期时间,我有很多投的错误(从的DateTime
到日期时间?
)。
I'm wondering what ?
means in C# ?
I'm seeing things like: DateTime?
or int?
. I suppose this is specific to C# 4.0?
I can't look for it in Google because I don't know the name of this thing.
The problem is I'm using DateTime and I have a lot of cast errors (from DateTime
to DateTime?
).
感谢您
推荐答案
这是一个速记书写可空< INT>
或可空< DateTime的>
。 Nullables 一起使用的值的类型不能为空(他们总是有一个值)。
It's a shorthand for writing Nullable<int>
or Nullable<DateTime>
. Nullables are used with value types that cannot be null (they always have a value).
有不特定于C#4的方式。
It is not specific to C#4 by the way.
您只能指定一个诠释?
到 INT
如果它有一个价值,所以你的$ C $ Ç将不得不做这样的事情:
You can only assign an int?
to an int
if it has a value, so your code would have to do things like:
int? n = 1;
int i = n ?? default(int); //or whatever makes sense
另外请注意,一个可空
有两个属性, hasValue的
和值
,您可以使用测试,如果一个值已设置并获得实际价值。
Also note that a Nullable
has two properties, HasValue
and Value
that you can use test if a value has been set and to get the actual value.
这篇关于C# - 基本问题:什么是“?”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!