vb.net 使整数为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3628757/
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
Make An Integer Null
提问by Nick LaMarca
I have an update function that updates an sql server db table through a dataset. One of the fields in the table is an integer and accepts null values. So when I am populating the update function I need a way to enter a null in when the function wants an integer.
我有一个更新函数,可以通过数据集更新 sql server db 表。表中的字段之一是整数并接受空值。因此,当我填充更新函数时,我需要一种在函数需要整数时输入空值的方法。
I tried to do it this way but _intDLocation = ""
throws an exception
我试图这样做,但 _intDLocation = ""
抛出异常
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer
If _dLocation <> "" Then
_intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
'NEED HELP HERE
_intDLocation = ""
End If
回答by Larsenal
Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer. Now _intDLocation is no longer a normal integer. It is an instance of Nullable(Of Integer)
.
整数不能设置为 Null。您必须通过在单词 Integer 后添加问号使整数“可空”。现在 _intDLocation 不再是一个普通的整数。它是 的一个实例Nullable(Of Integer)
。
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer?
If _dLocation <> "" Then
_intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
_intDLocation = Nothing
End If
Later on, if you want to check for null you can use this handy, readable syntax:
稍后,如果您想检查 null,您可以使用这个方便、易读的语法:
If _intDLocation.HasValue Then
DoSomething()
End If
In some cases you will need to access the value as an actual integer, not a nullable integer. For those cases, you simply access
在某些情况下,您需要将值作为实际整数而不是可以为空的整数来访问。对于这些情况,您只需访问
_intDLocation.Value
Read all about Nullable here.
在此处阅读有关 Nullable 的所有信息。
回答by Jason Evans
Try this:
尝试这个:
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Nullable(Of Integer)
If Not String.IsNullOrEmpty(_dLocation) Then
_intDLocation = Integer.Parse(_dLocation)
End If
回答by Tony Gardner
My application uses a lot of labels that start out blank (Text property), but need to be incremented as integers, so I made this handy function:
我的应用程序使用了很多以空白开头的标签(Text 属性),但需要以整数形式递增,所以我制作了这个方便的函数:
Public Shared Function Nullinator(ByVal CheckVal As String) As Integer
' Receives a string and returns an integer (zero if Null or Empty or original value)
If String.IsNullOrEmpty(CheckVal) Then
Return 0
Else
Return CheckVal
End If
End Function
This is typical example of how it would be used:
这是如何使用它的典型示例:
Dim Match_Innings As Integer = Nullinator(Me.TotalInnings.Text)
Enjoy!
享受!
回答by lumberHyman4
_intDLocation = Nothing