微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将VB.NET变量设置为C#的null

根据 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();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐