提问人:John89 提问时间:11/17/2023 最后编辑:John89 更新时间:11/18/2023 访问量:56
如何创建“=”运算符来检查结构类型是否为 null
How to create an "=" operator to check if a Structure type is null
问:
我以前从来没有遇到过创建操作员的问题,但这次我被难住了。我的目标是能够使用运算符来检查我的结构类型是否为 null。例:。我尝试了几种不同的失败方法,但没有成功找到任何关于我问题的文档。我不确定如何将对象标识符类型设置为空标识符:=
If myStruct = Nothing Then
PhoneNumber
结构中的运算符:
Public Shared Operator =(number As PhoneNumber, null As Nothing) As Boolean ' <== Error for type "Nothing": Keyword does not name a type.
Return IsDBNull(number)
End Operator
Public Shared Operator <>(number As PhoneNumber, null As Nothing) As Boolean ' <== Error for type "Nothing": Keyword does not name a type.
Return Not IsDBNull(number)
End Operator
检查结构是否为 null:
Friend Sub Foo(num as PhoneNumber)
If myStruct = Nothing Then
' Do something
Else
' Do something else
End If
End Sub
有没有可能做我想做的事情?如果是这样,你们能给我指出解决这个问题的方向吗?我更愿意了解这一切是如何工作的,但我很乐意接受解决方案/答案作为替代方案。
答:
0赞
Jon Roberts
11/18/2023
#1
归功于 @jmcilhinney 的评论,这段代码对我有用,没有错误:
Private Structure TelephoneNo
Public AreaCode As String
Public telno As String
End Structure
Private Sub foo(num As Nullable(Of TelephoneNo))
If num Is Nothing Then
' Do something
Else
' Do something else
End If
End Sub
评论
1赞
Craig
11/18/2023
您可以缩写为 .Nullable(Of TelephoneNo)
TelephoneNo?
评论
Structure
Nothing
DBNull
Object
DBNull
Nothing
PhoneNumber
DBNull
SomeValueType
Nullable(Of SomeValueType)
SomeValueType?
HasValue
True
Value