【问题标题】:What's the point in converting c# to vb.net of querying if the event is null?将 c# 转换为 vb.net 以查询事件是否为空有什么意义?
【发布时间】:2016-02-05 05:09:34
【问题描述】:

我截断了从 c# 转换为 vb.net 的代码。但是,vb.net 代码不允许我查询是否实例化了事件。这是c#代码:

    public event EventHandler<TreeModelEventArgs> NodesInserted;
    internal void OnNodeInserted(Node parent, int index, Node node)
    {
        if (NodesInserted != null)
        {
            TreeModelEventArgs args = new TreeModelEventArgs(GetPath(parent), new int[] { index }, new object[] { node });
            NodesInserted(this, args);
        }

    }

它“确认”的具体行是:

        if (NodesInserted!= null)

这是 vb.net 代码:

Public Event NodesInserted As EventHandler(Of TreeModelEventArgs) Implements ITreeModel.NodesInserted
Friend Sub OnNodeInserted(parent As Node, index As Integer, node As Node)
  If NodesInserted IsNot Nothing Then
    Dim args As New TreeModelEventArgs(GetPath(parent), New Integer() {index}, New Object() {node})
    RaiseEvent NodesInserted(Me, args)
  End If

End Sub

具体来说:

  If NodesInserted IsNot Nothing Then

返回一个错误,说我应该使用 RaiseEvent,当然我已经在使用了。

我的问题是,我什至需要检查 null 吗?如果 C# 中的事件不存在,它怎么可能被调用?我想我应该删除“If”语句,但这是一个复杂的项目,我可能会遗漏一些东西。专家可以帮助我吗?

【问题讨论】:

    标签: c# asp.net .net vb.net


    【解决方案1】:

    您不需要在 VB 中检查“无”,但如果您想要等价的, 您需要使用隐藏的事件字段:

    Public Event NodesInserted As EventHandler(Of TreeModelEventArgs)
    Friend Sub OnNodeInserted(ByVal parent As Node, ByVal index As Integer, ByVal node As Node)
        If NodesInsertedEvent IsNot Nothing Then 'yes - add the 'Event'
            Dim args As New TreeModelEventArgs(GetPath(parent), New Integer() { index }, New Object() { node })
            RaiseEvent NodesInserted(Me, args)
        End If
    End Sub
    

    正如我所说,VB 会以其他方式处理它,但有时您只是真的想知道是否有事件订阅者。

    【讨论】:

    • 好的,非常感谢您的回复,但现在我很困惑。如您所见,我确实引发了事件,我只是在检查 null 之后才这样做。你能告诉我引发事件然后再次引发事件的代码是什么样的吗?我没有看到它...我将如何完成与 c# 中所做的等效的工作?
    • 所有空检查都是确保您至少拥有一个订阅的处理程序。如果您在 VB 中使用“RaiseEvent”而不进行空值检查,VB 会处理它并防止异常 - 即,VB 会为您进行空值检查。但是,使用以“事件”结尾的隐藏(几乎未记录)字段也可以让您检查订阅者。
    • C# 示例仅引发一次事件。代码“NodesInserted != null”不是检查函数的返回值是否为 null,而是检查是否有事件处理程序正在侦听该事件。看起来类似于 VB 中的函数调用,但它做的事情不同。
    • @DaveDoknjas,您能否发布一个指向有关 eventNameEvent 字段的参考的链接。我知道你对它的存在是正确的,但我从未见过官方提及它。
    • @TnTinMn:我希望我能找到它 - 我花了几分钟寻找 Microsoft 文档但找不到它 - 我知道它在某个地方(我知道它有效,我知道我已经看过它的文档一次)。
    【解决方案2】:

    VB.net 与 C# 的不同之处在于它会在您调用 RaiseEvent 时为您进行检查。但是,如果您有兴趣保留上面的大部分代码,请将“NodesInserted”上的无检查更改为“NodesInsertedEvent”。因此,NodesInsertedEvent 变量是自动创建的。

    If NodesInsertedEvent IsNot Nothing Then
    ...
    End If
    

    与此答案类似:https://stackoverflow.com/a/11142499/3325680

    【讨论】:

    • 感谢丹佛!这正是我一直在寻找的。我希望我能分享这些观点,因为你很清楚地回答了这个问题,但戴夫是第一个,他确实提到了“事件”的事情,尽管我不明白。感谢你们俩!其实,现在我想了想,你确实回答了这个问题。戴夫也做了,但我不明白“事件”的添加。我从您的代码中看到您将其添加到事件名称的 END 中......再次,希望我可以拆分点。对不起戴夫。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    相关资源
    最近更新 更多