vb.net 为什么我不能检查“DateTime”是否为“Nothing”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5869661/
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
Why can't I check if a 'DateTime' is 'Nothing'?
提问by Muleskinner
In VB.NET, is there a way to set a DateTime
variable to "not set"? And why is it possible to set a DateTime
to Nothing
, but notpossible to check if it is Nothing
? For example:
在 VB.NET 中,有没有办法将DateTime
变量设置为“未设置”?为什么可以将 a 设置DateTime
为Nothing
,但无法检查是否为Nothing
?例如:
Dim d As DateTime = Nothing
Dim boolNotSet As Boolean = d Is Nothing
The second statement throws this error:
第二个语句抛出这个错误:
'Is' operator does not accept operands of type 'Date'. Operands must be reference or
nullable types.
回答by jeroenh
This is one of the biggest sources of confusion with VB.Net, IMO.
这是与 VB.Net、IMO 混淆的最大来源之一。
Nothing
in VB.Net is the equivalent of default(T)
in C#: the default value for the given type.
Nothing
在 VB.Net 中相当于default(T)
在 C# 中:给定类型的默认值。
- For value types, this is essentially the equivalent of 'zero':
0
forInteger
,False
forBoolean
,DateTime.MinValue
forDateTime
, ... - For reference types, it is the
null
value (a reference that refers to, well, nothing).
- 对于值类型,这本质上等同于“零”:
0
forInteger
,False
forBoolean
,DateTime.MinValue
forDateTime
, ... - 对于引用类型,它是
null
值(一个引用,好吧,什么都没有)。
The statement d Is Nothing
is therefore equivalent to d Is DateTime.MinValue
, which obviously does not compile.
d Is Nothing
因此d Is DateTime.MinValue
,该语句等效于,显然不能编译。
Solutions: as others have said
解决方案:正如其他人所说
- Either use
DateTime?
(i.e.Nullable(Of DateTime)
). This is my preferred solution. - Or use
d = DateTime.MinValue
or equivalentlyd = Nothing
- 要么使用
DateTime?
(即Nullable(Of DateTime)
)。这是我首选的解决方案。 - 或使用
d = DateTime.MinValue
或等效d = Nothing
In the context of the original code, you could use:
在原始代码的上下文中,您可以使用:
Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = d.HasValue
A more comprehensive explanation can be found on Anthony D. Green's blog
可以在Anthony D. Green 的博客上找到更全面的解释
回答by John M Gant
DateTime is a value type, which is why it can't be null. You can check for it to be equal to DateTime.MinValue
, or you can use Nullable(Of DateTime)
instead.
DateTime 是一种值类型,这就是它不能为 null 的原因。您可以检查它是否等于DateTime.MinValue
,或者您可以使用它Nullable(Of DateTime)
。
VB sometimes "helpfully" makes you think it's doing something it's not. When it lets you set a Date to Nothing, it's really setting it to some other value, maybe MinValue.
VB 有时“有帮助”让你认为它在做一些它没有做的事情。当它允许您将 Date 设置为 Nothing 时,实际上是将其设置为其他值,可能是 MinValue。
See this questionfor an extensive discussion of value types vs. reference types.
有关值类型与引用类型的广泛讨论,请参阅此问题。
回答by Cheeso
DateTime is a value type, which means it always has some value.
DateTime 是一个值类型,这意味着它总是有一些值。
It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".
它就像一个整数——它可以是 0、1 或小于零,但它永远不能是“无”。
If you want a DateTime that can take the value Nothing, use a Nullable DateTime.
如果您想要一个可以取值为 Nothing 的 DateTime,请使用 Nullable DateTime。
回答by DavidRR
Some examples on working with nullable DateTime
values.
有关使用可为空DateTime
值的一些示例。
(See Nullable Value Types (Visual Basic)for more.)
(有关更多信息,请参阅可空值类型 (Visual Basic)。)
'
' An ordinary DateTime declaration. It is *not* nullable. Setting it to
' 'Nothing' actually results in a non-null value.
'
Dim d1 As DateTime = Nothing
Console.WriteLine(String.Format("d1 = [{0}]\n", d1))
' Output: d1 = [1/1/0001 12:00:00 AM]
' Console.WriteLine(String.Format("d1 is Nothing? [{0}]\n", (d1 Is Nothing)))
'
' Compilation error on above expression '(d1 Is Nothing)':
'
' 'Is' operator does not accept operands of type 'Date'.
' Operands must be reference or nullable types.
'
' Three different but equivalent ways to declare a DateTime
' nullable:
'
Dim d2? As DateTime = Nothing
Console.WriteLine(String.Format("d2 = [{0}][{1}]\n", d2, (d2 Is Nothing)))
' Output: d2 = [][True]
Dim d3 As DateTime? = Nothing
Console.WriteLine(String.Format("d3 = [{0}][{1}]\n", d3, (d3 Is Nothing)))
' Output: d3 = [][True]
Dim d4 As Nullable(Of DateTime) = Nothing
Console.WriteLine(String.Format("d4 = [{0}][{1}]\n", d4, (d4 Is Nothing)))
' Output: d4 = [][True]
Also, on how to check whether a variable is null(from Nothing (Visual Basic)):
另外,关于如何检查变量是否为空(来自Nothing (Visual Basic)):
When checking whether a reference (or nullable value type) variable is null, do not use= Nothing
or<> Nothing
. Always useIs Nothing
orIsNot Nothing
.
回答by Mahavirsinh Padhiyar
You can also use below just simple to check:
您也可以使用下面的简单检查:
If startDate <> Nothing Then
your logic
End If
It will check that the startDate variable of DateTime datatype is null or not.
它将检查 DateTime 数据类型的 startDate 变量是否为空。
回答by Sukhi
You can check this like below :
您可以像下面这样检查:
if varDate = "#01/01/0001#" then
' blank date. do something.
else
' Date is not blank. Do some other thing
end if
回答by sscheider
In any programming language, be careful when using Nulls. The example above shows another issue. If you use a type of Nullable, that means that the variables instantiated from that type can hold the value System.DBNull.Value; not that it has changed the interpretation of setting the value to default using "= Nothing" or that the Object of the value can now support a null reference. Just a warning... happy coding!
在任何编程语言中,使用 Null 时都要小心。上面的例子显示了另一个问题。如果使用 Nullable 类型,则意味着从该类型实例化的变量可以保存值 System.DBNull.Value;并不是它改变了使用“= Nothing”将值设置为默认值的解释,或者值的对象现在可以支持空引用。只是一个警告......快乐编码!
You could create a separate class containing a value type. An object created from such a class would be a reference type, which could be assigned Nothing. An example:
您可以创建一个包含值类型的单独类。从这样的类创建的对象将是一个引用类型,它可以被赋值为 Nothing。一个例子:
Public Class DateTimeNullable
Private _value As DateTime
'properties
Public Property Value() As DateTime
Get
Return _value
End Get
Set(ByVal value As DateTime)
_value = value
End Set
End Property
'constructors
Public Sub New()
Value = DateTime.MinValue
End Sub
Public Sub New(ByVal dt As DateTime)
Value = dt
End Sub
'overridables
Public Overrides Function ToString() As String
Return Value.ToString()
End Function
End Class
结束类
'in Main():
'在主():
Dim dtn As DateTimeNullable = Nothing
Dim strTest1 As String = "Falied"
Dim strTest2 As String = "Failed"
If dtn Is Nothing Then strTest1 = "Succeeded"
dtn = New DateTimeNullable(DateTime.Now)
If dtn Is Nothing Then strTest2 = "Succeeded"
Console.WriteLine("test1: " & strTest1)
Console.WriteLine("test2: " & strTest2)
Console.WriteLine(".ToString() = " & dtn.ToString())
Console.WriteLine(".Value.ToString() = " & dtn.Value.ToString())
Console.ReadKey()
' Output:
'test1: Succeeded()
'test2: Failed()
'.ToString() = 4/10/2012 11:28:10 AM
'.Value.ToString() = 4/10/2012 11:28:10 AM
Then you could pick and choose overridables to make it do what you need. Lot of work - but if you really need it, you can do it.
然后,您可以挑选可覆盖的对象以使其满足您的需求。很多工作 - 但如果你真的需要它,你可以做到。
回答by George Filippakos
A way around this would be to use Object datatype instead:
解决此问题的一种方法是改用 Object 数据类型:
Private _myDate As Object
Private Property MyDate As Date
Get
If IsNothing(_myDate) Then Return Nothing
Return CDate(_myDate)
End Get
Set(value As Date)
If date = Nothing Then
_myDate = Nothing
Return
End If
_myDate = value
End Set
End Property
Then you can set the date to nothing like so:
然后您可以将日期设置为空:
MyDate = Nothing
Dim theDate As Date = MyDate
If theDate = Nothing Then
'date is nothing
End If