gpt4 book ai didi

c# - 实际上什么都不是 - 它是如何转换的

转载 作者:行者123 更新时间:2023-11-30 23:24:11 24 4
gpt4 key购买 nike

我有一个带有测试方法的 VB 类库。这将返回一个整数(有时 Nothing 将被返回)。

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

这里 Nothing 将被转换为 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 then null will be assigned.

最佳答案

正如我在问题中提到的(我也假设),Nothing表示任何数据类型的默认值 (C# default(T))。对于引用类型,默认值为空引用。对于值类型,默认值取决于值类型是否可为空。

在我的 VB 代码中,该方法的返回值是 Integer(值类型),因此它的默认值 0 不会是任何值。这就是 0 也被分配给动态类型的原因。但它不是 null 的替代品,也不等同于 null

关于c# - 实际上什么都不是 - 它是如何转换的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37957974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com