C# 为什么私有变量定义上有一个问号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2326158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:26:28  来源:igfitidea点击:

Why is there a questionmark on the private variable definition?

c#nullable

提问by Booser

I am reading an article about the MVVP Pattern and how to implement it with WPF. In the source code there are multiple lines where I cannot figure out what the question marks in it stand for.

我正在阅读一篇关于 MVVP 模式以及如何使用 WPF 实现它的文章。在源代码中有多行,我无法弄清楚其中的问号代表什么。

private DateTime? _value;

What does the ?mean in the definition? I tried to find it in the help from VS but failed.

?定义中的意思是什么?我试图在 VS 的帮助中找到它,但失败了。

采纳答案by David Morton

It's a nullable value. Structs, by default, cannot be nullable, they must have a value, so in C# 2.0, the Nullable<T>type was introduced to the .NET Framework.

这是一个可以为空的值。默认情况下,结构不能为空,它们必须有一个值,因此在 C# 2.0 中,该Nullable<T>类型被引入到 .NET Framework 中。

C# implements the Nullable<T>type with a piece of syntactic sugar, which places a question mark after the type name, thus making the previously non-nullable type, nullable.

C#Nullable<T>用一段语法糖实现了类型,在类型名称后面放了一个问号,从而使之前不可为空的类型可以为空。

回答by Anvaka

That means the type is Nullable.

这意味着类型是Nullable

回答by Thomas Levesque

It means that the field is a Nullable<DateTime>, i.e. a DateTimethat can be null

这意味着该字段是 a Nullable<DateTime>,即 aDateTime可以为空

回答by Svetlozar Angelov

This is a nullable type, you can assign null to it

这是一个可为空的类型,您可以为其分配空值

回答by Raja

Private DateTime? _value - means that the _value is nullable. check out this link for a better explanation.

私人日期时间?_value - 表示 _value 可以为空。查看此链接以获得更好的解释。

http://davidhayden.com/blog/dave/archive/2005/05/23/1047.aspx

http://davidhayden.com/blog/dave/archive/2005/05/23/1047.aspx

Hope this helps.

希望这可以帮助。

Thanks, Raja

谢谢,拉贾

回答by Asad

cannot be null

不能为空

DateTime                        
DateTime dt = null;   // Error: Cannot convert null to 'System.DateTime'
                         because it is a  non-nullable value type 

can be null

可以为空

DateTime? / Nullable<DateTime>  
DateTime? dt = null;  // no problems