VB.NET:如何让事件像在C#中那样返回一个值? [英] VB.NET: How can I have events return a value like I can in C#?

查看:76
本文介绍了VB.NET:如何让事件像在C#中那样返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我可以这样做:

In C#, I can do this:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Class1 c1 = new Class1();

        c1.OnNeedInt += new Class1.NeedInt(c1_OnNeedInt);

        int i = c1.GetInt();
    }

    int c1_OnNeedInt()
    {
        return 1;
    }
}

public class Class1
{
    public delegate int NeedInt();
    public event NeedInt OnNeedInt;

    public int GetInt()
    {
        return OnNeedInt == null ? 0 : OnNeedInt();
    }
}

注意该行 int i = c1.GetInt(); 。我似乎无法让VB.NET 4.0做类似的事情。有帮助吗?

Notice the line int i = c1.GetInt();. I can't seem to get VB.NET 4.0 to do something similiar. Any help?

推荐答案

我找到了问题的答案。在我的ASP.NET用户控件继承的基类中,我有以下内容:

I found an answer to my issue. In the base class that my ASP.NET user controls inherit, I have this:

Dim _Connection As MyConnection
Public Property Connection As MyConnection
    Get
        If _Connection Is Nothing Then
            RaiseEvent OnNeedConnection(_Connection)
        End If
        Return _Connection
    End Get
    Set(value As MyConnection)
        _Connection = value
    End Set
End Property

Public Delegate Sub NeedConnection(ByRef Connection As MyConnection)
Public Event OnNeedConnection As NeedConnection

在后面的Web表单中,我手动将其连接到此:

In my web form codebehind, I wire it up manually to this:

Sub ServeConnection(ByRef Connection As MyConnection)

    Connection = oConn

End Sub

实际的连接托管在Webform的代码隐藏中,但是我有几个用户控件需要使用此连接。任何时候,任何用户控件都需要连接时,其基类都会请求该连接,并且宿主页面会为其提供服务。通过 ByRef 关键字使之成为可能。

The actual connection is hosted on the webform's codebehind, but I have several user controls that need to use this connection. Any time any of the user controls need the connection, their base class requests it and the host page serves it. This is made possible by the ByRef keyword.

这是我可以放在一起的最接近的C#等价物。

This is the closest C# equivalent I could put together.

这篇关于VB.NET:如何让事件像在C#中那样返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆