VB.NET 缺少 isNull()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/642435/
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
VB.NET missing isNull()?
提问by Tom
I like to confirm that array is created, how can it be done? There is no nul keyword?
我想确认数组已创建,怎么办?有没有nul关键字?
Dim items As Array = str.Split("|")
if (items=null) then ???
回答by Matthew Dresser
To check if an object is null in VB.Net you need to use the Nothing keyword. e.g.
要检查 VB.Net 中的对象是否为空,您需要使用 Nothing 关键字。例如
If (items is Nothing) Then
'do stuff
End If
However string.Split() never returns null, so you should check the input string for null rather than the items array. Your code could be changed to something like:
但是 string.Split() 永远不会返回 null,因此您应该检查输入字符串是否为 null 而不是 items 数组。您的代码可以更改为:
If Not String.IsNullOrEmpty(str) Then
Dim items As Array = str.Split("|")
'do stuff
End If
回答by KevB
Try using String.IsNullOrEmpty
on your string variable before splitting it. If you attempt to split the variable with nothing in the string the array will still have one item in it (an empty string), therefore your IsNothing
checks on the array will return false.
String.IsNullOrEmpty
在拆分之前尝试在您的字符串变量上使用。如果您尝试在字符串中不包含任何内容的情况下拆分变量,则数组中仍将包含一项(空字符串),因此您IsNothing
对数组的检查将返回 false。
回答by John Saunders
String.Split can never return null. At worst, it can return an array with no elements.
String.Split 永远不会返回 null。最坏的情况是,它可以返回一个没有元素的数组。
回答by Jim H.
Use "Is Nothing" to test for Null in VB.NET.
在 VB.NET 中使用“Is Nothing”来测试 Null。
If items Is Nothing Then
End If
回答by Guffa
The keyword for null in VB is Nothing
.
VB 中 null 的关键字是Nothing
.
However, this is not what you want to use in this case. The Split
method never returns a null reference. It always returns a string array that has at least one item. If the string that you split was empty, you get an array containing one string with the length zero.
但是,在这种情况下,这不是您想要使用的。该Split
方法从不返回空引用。它总是返回一个至少包含一项的字符串数组。如果拆分的字符串为空,则会得到一个包含长度为零的字符串的数组。
So, to check if you get that as result you would do:
所以,要检查你是否得到了结果,你会这样做:
Dim items As String() = str.Split("|")
If items.Length = 1 and items(0).Length = 0 Then ...
It's of course easier to check the input first:
首先检查输入当然更容易:
If str.Length = 0 Then ...
回答by D. Kermott
For a one liner do this:
对于单班轮,请执行以下操作:
destinationVariable = if(myvar is nothing, "", myvar)