根据Visual Basic的 Nothing MSDN 条目,Nothing 表示数据类型的默认值。
一些人已经指出 "some"," ...
这给我最近正在处理的多语言解决方案中带来了一些异常行为。具体而言,当 VB.NET 异步方法返回
是否可以在 VB.NET 项目中设置变量为 C# 的
这里有一段代码片段没有按预期工作。C# 项目将 VB.NET 项目作为引用导入。
VB.NET 方面:
当VB.NET的
如何有效地将
一些人已经指出 "some"," ...
Nothing
关键字实际上等同于 C# 的 default(T)
关键字"。这给我最近正在处理的多语言解决方案中带来了一些异常行为。具体而言,当 VB.NET 异步方法返回
Nothing
时,我在 C# 端遇到了不止几次的 TargetInvocationException
。是否可以在 VB.NET 项目中设置变量为 C# 的
null
并能够在 C# 和 VB.NET 中测试该 null
值?
这里有一段代码片段没有按预期工作。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
?
.ToString()
,这可能会导致抛出“空值”错误。另外,告诉我们你得到的错误信息,"falls on its head"并不像"system.whatever返回了一个值X,而它期望的是Y"那样具有信息量。 - NikerymInnerException
是什么? - WillTargetInvocationException
,其消息为“在 mscorlib.dll 中发生了类型为 'System.Reflection.TargetInvocationException' 的第一次机会异常”。Visual Studio 显示“源不可用”页面,也没有可用的堆栈跟踪。 - Alex Essilfieawait task;
应该失败。DoSomething()
方法始终返回非空对象,因此task
本身始终非空,因此await task
应始终有效。 结果为null,但您从未在第三个示例中使用它,因此它为null并不是问题。 除此之外,un-lucky的答案解决了您的问题:与“无”相比,“null”没有问题…您也不允许在VB中取消引用“无”! - Peter Duniho