我有一个带有测试方法的 VB 类库。它将返回一个整数(有时什么也不会返回
)。
Public Class Class1
Public Function testMethod() As Integer
'Some code here
Return Nothing
End Function
End Class
如果我在 VB 项目中调用该方法,一切都会按预期正常工作。例如:
Dim output As String = testMethod().ToString() ' Works fine and output =""
但是当我在 C# 应用程序中通过创建对象来调用该方法时,当返回值为 Nothing
时,它将抛出 null 错误。
VBTestLib.Class1 classObject = new VBTestLib.Class1();
string objectStringValue = classObject.testMethod().ToString(); // Error
这意味着 Nothing
将被转换为 null
(不允许 null.ToString()
)。现在考虑下一个例子:
int objectIntValue = classObject.testMethod(); // objectIntValue = 0
此处不会将任何内容转换为 int 的默认值 (0
)。我使用dynamic
扩展了测试,然后分配的值为0
。即,
dynamic objectDynamicValue = classObject.testMethod();// objectDynamicValue = 0
所以我的问题是,什么是Nothing
?当分配给 C# 类型时将如何转换?或者我应该得出这样的结论:
If a VB Method returns
Nothing
and the value is assigned to a C# variable of value type then the default value of method's return type will be assigned. And if it is assigned to a reference type variable thennull
will be assigned.
最佳答案
正如我在问题中提到的(我也假设),Nothing
表示任何数据类型的默认值 (C# default(T)
)。对于引用类型,默认值为空引用。对于值类型,默认值取决于值类型是否可为空。
在我的 VB 代码中,该方法的返回值是 Integer(值类型),因此它的默认值 0
不会是任何内容。这就是 0
也被分配给动态类型的原因。但它不是 null
的替代品,也不等同于 null
。
关于c# - 实际上什么是Nothing——它是如何转换的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37957974/