根据
MSDN entry for Nothing (Visual Basic)
Nothing represents the default value of a data type.
some还注意到“…… Nothing关键字实际上等同于C#的default(T)
关键字”.
这在我最近一直在研究的多语言解决方案中给了我一些异常行为.具体来说,当VB.NET异步方法返回Nothing时,我已经在C#端抛出了多个TargetInvocationExceptions.
是否可以将VB.NET项目中的变量设置为C#的null,并且能够在C#和VB.NET中测试此空值.
这是一个表现不尽如人意的片段. C#项目导入VB.NET项目作为参考.
VB.NET方面
Public Function DoSomething() As Task(Of Object) Dim tcs = New TaskCompletionSource(Of Object) Dim params = Tuple.Create("parameters",tcs) AnotherMethod(params) Return tcs.Task End Function Public Sub AnotherMethod(params As Tuple(Of String,TaskCompletionSource(Of Object)) ' do some activities If result = "Success" Then params.Item2.SetResult("we were successful") ' result can also be of different type Else params.Item2.SetResult(Nothing) ' could this be the source of the exception? End If End Sub
C#边
public async void AwaitSomething1() { var result = ""; result = (await DoSomething()).ToString(); // fails if Result is Nothing } public async void AwaitSomething2() { var result = ""; result = (string)(await DoSomething()); // fails if Result is Nothing } public async void AwaitSomething3() { var task = DoSomething(); await task; // also fails if Result is Nothing }
当VB.NET的AnotherMethod成功时,没有抛出异常.然而,当它没有成功并且tcs的结果被设置为Nothing时,一切都落到了它的头上.
如何在不导致异常的情况下有效地将SetResult设置为Nothing,否则,我如何将SetResult设置为C#的null?
解决方法
这不是因为从Nothing转换为null.在这里,我有一些示例,其中C#接受Nothing为null:
Vb类库代码:
Public Class ClassVb Public Function Dosomething() As Task(Of Object) Return Nothing End Function End Class
调用此类库的C#:
using vbclassLib; class Program { static void Main(string[] args) { ClassVb classLibObj = new ClassVb(); var result = classLibObj.Dosomething();//result=null } }
哪个工作正常并给出result = null,即.,Nothing被转换为null
让我来看看你的情景:
在您的场景中,当函数返回Nothing时,它肯定会转换为null但.ToString()方法或await()无法处理null,这就是您获得异常的原因.
> null.ToString()或(null).ToString()表示运算符’.’不能应用于’< null>‘类型的操作数.
c#不允许使用await(null),它表示不能等待null.
这可能对您有所帮助:
ClassVb classLibObj = new ClassVb(); var temp = classLibObj.Dosomething(); var result = temp == null ? "" : temp.ToString();