c# - Null(在 C# 中)与 Nothing(在 vb.net 中)

标签 c# vb.net

C# NULL 与 vb.net Nothing 有何不同?

Console.WriteLine(Nothing = "") => True

对比

Console.WriteLine(null==""); => False

我的理解是 nullNothing 是一样的。但是上面的代码清楚地说明了它不是。

VB.NET 中 C# null 的等价物是什么?

最佳答案

您选择了 little bid complex example 来测试 vb.net 中的 Nothing 和 c# 中的 null 之间的区别

来自关于 Nothing 的 Visual basic 语言规范:

Nothing is a special literal; it does not have a type and is convertible to all types in the type system, including type parameters. When converted to a particular type, it is the equivalent of the default value of that type.

如果您阅读 default value expressions 的描述从 Microsoft 文档中,您会注意到 vb.net 中的 Nothing 和 C# 中的 default(T) 具有相似的行为。

例如

Dim isSomething As Boolean = Nothing ' = False
Dim amount As Integer = Nothing ' = 0
Dim value As String = Nothing ' = null (notice not empty string!)

证明字符串的默认值不是空字符串,因为这里的许多评论/答案都保留

Dim value As String = Nothing
If value.Equals("") Then ' will throw NullReferenceException

End If 

Nothing 与空字符串 """=" 运算符进行比较是 vb.net 的特例,因为 Nothing 的字符串将评估为 null

来自关于 String 类型的关系运算符的 Visual basic 语言规范:

The operators return the result of comparing the two values using either a binary comparison or a text comparison. The comparison used is determined by the compilation environment and the Option Compare statement. A binary comparison determines whether the numeric Unicode value of each character in each string is the same. A text comparison does a Unicode text comparison based on the current culture in use on the .NET Framework. When doing a string comparison, a null reference is equivalent to the string literal "".

要在 vb.net 中检查字符串相等性,您应该使用 String.Equals 方法或 Is 运算符。

基于上述语言规范

My understanding was that both null and Nothing are same. But above code clearly explains it is not.

它们不一样,vb.net中的Nothing等同于C#中的default(T)

What is the equivalent of C# null in VB.NET?

在 C# 中,您不能将 null 设置为值类型,因此对于引用类型 (String) 等价于 C# null 在 vb.net 中将成为Nothing
例如 (null == default(String))

关于c# - Null(在 C# 中)与 Nothing(在 vb.net 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44192049/

相关文章:

c# - .net onpaint 垂直同步

c++ - 从我在 C++ 中不拥有的应用程序读取内存(vb.net 中的示例)

c# - 这个修剪代码会失败吗?

c# - 通过传递的参数查找枚举值

vb.net运行时按钮和 "AddressOf "括号

mysql - 在调用 Read() INSERT 之前访问字段的尝试无效

vb.net - 如何在 vb.net 中使用 lambda 删除列表的指定项目

c# - 为什么向我的 WCF 服务操作添加参数会起作用?

c# - 如何将项目添加到 ASP.NET 中的下拉列表?

c# - UWP-App 创建的文件未在 Windows 10 1803 中编制索引