题
我有一个可为空的属性,并且我想返回一个空值。我如何在 VB.NET 中做到这一点?
目前我使用这个解决方案,但我认为可能有更好的方法。
Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
If Current.Request.QueryString("rid") <> "" Then
Return CInt(Current.Request.QueryString("rid"))
Else
Return (New Nullable(Of Integer)).Value
End If
End Get
End Property
解决方案
您在寻找关键字“Nothing”吗?
其他提示
是的,在 VB.NET 中它是 Nothing,在 C# 中它是 null。
Nullable 泛型数据类型使编译器可以将“Nothing”(或 null)值分配给值类型。如果没有明确地写出来,你就无法做到这一点。
Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
If Current.Request.QueryString("rid") <> "" Then
Return CInt(Current.Request.QueryString("rid"))
Else
Return Nothing
End If
End Get
End Property
或者这就是我使用的方式,说实话 ReSharper 教了我:)
finder.Advisor = ucEstateFinder.Advisor == "-1" ? (long?)null : long.Parse(ucEstateFinder.Advisor);
在上面的分配中,如果我直接将 null 分配给 finder.Advisor*(long?)* 就不会有问题。但如果我尝试使用 if 子句,我需要像这样转换它 (long?)null
.
虽然 Nothing
可以使用,你的“现有”代码几乎是正确的;只是不要试图获得 .Value
:
Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
If Current.Request.QueryString("rid") <> "" Then
Return CInt(Current.Request.QueryString("rid"))
Else
Return New Nullable(Of Integer)
End If
End Get
End Property
如果您碰巧想将其减少到 If
表达:
Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
Return If(Current.Request.QueryString("rid") <> "", _
CInt(Current.Request.QueryString("rid")), _
New Nullable(Of Integer))
End Get
End Property
不隶属于 StackOverflow