根据MSDN entry for Nothing (Visual Basic)
some还指出“...... Nothing
关键字实际上等效于C#的 default(T)
关键字”。
这一直使我在最近一直在研究的多语言解决方案中出现了一些异常行为。具体来说,当VB.NET异步方法返回TargetInvocationException
时,我在C#端抛出了许多Nothing
。
是否可以在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
? 最佳答案
这不是因为从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 is converted as null
让我来谈谈您的情况:
在您的方案中,当函数返回
Nothing
时,它肯定会转换为null
,但是.ToString()
方法或await()
无法处理null
,这就是您获取异常的原因。null.ToString()
或(null).ToString()
表示The operator '.' cannot be applied to operand of type '<null>'
。 await(null)
表示c#
不允许使用cannot await null
。 这可能会帮助您:
ClassVb classLibObj = new ClassVb();
var temp = classLibObj.Dosomething();
var result = temp == null ? "" : temp.ToString();
关于c# - 将VB.NET变量设置为C#的null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32132355/