[英]When does Microsoft.Win32.OpenFileDialog.ShowDialog() return null?
OpenFileDialog 's ShowDialog method returns a nullable boolean, set to true if the user clicked OK or false if he clicked Cancel. OpenFileDialog的ShowDialog方法返回一个可以为空的布尔值,如果用户单击OK则设置为true,如果单击Cancel,则设置为false。 When does it return null
? 什么时候返回null
? The documentation does not say. 文档没有说。
This is stated in the questions linked below, but I'll mention here that Programming WPF (Chris Sells, Ian Griffiths) says: 这在下面的问题中有说明,但我在这里会提到编程WPF(Chris Sells,Ian Griffiths)说:
ShowDialog will always return true or false. ShowDialog将始终返回true或false。 ... Only after a dialog has been shown but before it's been closed is DialogResult null. ...只有在显示对话框之后但在关闭之前,DialogResult为null。
Similar question: When would ShowDialog() return null? 类似的问题: ShowDialog()什么时候会返回null?
And: Why is DialogResult a nullable bool in WPF? 并且: 为什么DialogResult在WPF中是一个可以为空的bool?
According to the .NET reflector , Microsoft.Win32.OpenFileDialog.ShowDialog
is implemented by a base class, Microsoft.Win32.CommonDialog
. 根据.NET反射器 , Microsoft.Win32.OpenFileDialog.ShowDialog
由基类Microsoft.Win32.CommonDialog
。 That implementation has only one return clause: 该实现只有一个return子句:
return new bool?(this.RunDialog(activeWindow));
RunDialog
returns a bool
, not a bool?
RunDialog
返回一个bool
,而不是一个bool?
. 。
bool?
is just a C# shorthand for System.Nullable<bool>
. 只是System.Nullable<bool>
的C#简写 。 The constructor of System.Nullable<bool>
, according to reflector again, sets the value of the nullable to its parameter, and marks its hasValue property as true. System.Nullable<bool>
的构造函数,再次根据反射器,将nullable的值设置为其参数,并将其hasValue属性标记为true。
So... you shouldn't ever get a null
result. 所以...你不应该得到一个null
结果。 A quick test confirms that closing the dialog without canceling (red x button) indeed returns a false
value, not a null
. 快速测试确认关闭对话框而不取消(红色x按钮)确实返回false
值,而不是null
。
The Windows Forms version of OpenFileDialog returns a DialogResult, which has a wider range of values . OpenFileDialog的Windows窗体版本返回一个DialogResult,它具有更广泛的值 。
My guess is that OpenFileDialog returns bool? 我的猜测是OpenFileDialog返回bool? to be consistent with other WPF dialogs that actually can return a null result. 与其他实际可以返回null结果的WPF对话框一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.