没有任何东西代表数据类型的默认值。
也有人注意到“ ...Nothing
关键字实际上等同于 C# 的default(T)
关键字”。
这在我最近一直在研究的多语言解决方案中给了我一些异常行为。具体来说,TargetInvocationException
当 VB.NET 异步方法返回时,我在 C# 端抛出了多个 s Nothing
。
是否可以将 VB.NET 项目中的变量设置为 C#,null
并能够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
}
AnotherMethod
VB.NET成功时不会抛出异常。但是,当它不成功并且tcs
' 的结果设置为 时Nothing
,一切都落在了它的头上。
我怎样才能有效SetResult
地Nothing
不导致异常,否则,我怎么能SetResult
到 C# 的null
?