Ale*_*fie 5 c# vb.net null nothing
什么都不代表数据类型的默认值.
一些人也注意到"...... 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
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
VB.NET AnotherMethod
成功时没有异常抛出.然而,当它没有成功并且tcs
结果被设定时Nothing
,一切都落到了它的头上.
如果没有导致异常,我怎么能有效地SetResult
完成Nothing
,否则,我怎么能SetResult
去C#null
?
这不是因为从Nothing
到的转换null
。Nothing
这里我为您提供了一些 C#接受的示例null
:
Vb类库代码:
Public Class ClassVb
Public Function Dosomething() As Task(Of Object)
Return Nothing
End Function
End Class
Run Code Online (Sandbox Code Playgroud)
调用该类库的 C# :
using vbclassLib;
class Program
{
static void Main(string[] args)
{
ClassVb classLibObj = new ClassVb();
var result = classLibObj.Dosomething();//result=null
}
}
Run Code Online (Sandbox Code Playgroud)
效果很好并且给出result=null
,即,Nothing is converted as null
让我来看看你的场景:
在您的场景中,当函数返回时,Nothing
它肯定会转换为null
but.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();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
562 次 |
最近记录: |