关于c#:事件处理程序问题

Event Handler issue

我在网上找到了一些C代码。我使用telerik代码转换器转换为vb.net。下面的代码有错误

Closed is already declared as 'public Even Closed(Sender as object, e as System.EventArgs)' in this class.

同样的错误也会出现在图中。有人有什么想法要解决吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #Region"Events"
    Public Event Closed As EventHandler
    Public Event Shown As EventHandler

    Protected Overridable Sub closed(e As EventArgs)
        Dim handler As EventHandler = Closed

        RaiseEvent handler(Me, e)
    End Sub

    Protected Overridable Sub shown(e As EventArgs)
        Dim handler As EventHandler = Shown

        RaiseEvent handler(Me, e)
    End Sub
#End Region

这是C代码I转换为VB。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#region Events
    public event EventHandler Closed;
    public event EventHandler Shown;

    protected virtual void closed(EventArgs e)
    {
        EventHandler handler = Closed;

        if (handler != null) handler(this, e);
    }

    protected virtual void shown(EventArgs e)
    {
        EventHandler handler = Shown;

        if (handler != null) handler(this, e);
    }
    #endregion


在我看来,这是因为vb.net不区分大小写,这意味着一个项目shown等同于一个项目shown

您可以通过重命名(最好使用重构工具)其中一个事件来解决问题,这样名称冲突就不会出现。您最好在C项目级别执行此操作,然后再次运行您的跨编译器工具以生成等效的vb.net代码。


这里有两个问题。

首先,如果您使用winforms,那么System.Windows.Forms已经有Closed事件与您正在创建的事件冲突。因此,如果要隐藏,则必须通过声明Shadows来隐藏事件。但是,如果您在一个普通类(它不是从Form派生的)中声明这一点,则无需担心。

1
2
Public Shadows Event Closed As EventHandler
Public Shadows Event Shown As EventHandler

其次,属性名和事件名不能相同。在这方面,vb.net不区分大小写。所以您应该按照以下方式重构名称。

1
2
3
4
5
6
7
8
9
10
Public Event Closed As EventHandler
Public Event Shown As EventHandler

Protected Overridable Sub whenClosed(ByVal e As EventArgs)
    RaiseEvent Closed(Me, e)
End Sub

Protected Overridable Sub whenShown(ByVal e As EventArgs)
    RaiseEvent Shown(Me, e)
End Sub