Преобразование кода обработки событий из C # в VB.NET - PullRequest
1 голос
/ 16 декабря 2011

Я пытаюсь преобразовать этот код, написанный на C #, в VB:

// Initialize the Message Broker Events
(Application.Current as App).MessageBroker.MessageReceived += new MessageReceivedEventHandler(MessageBroker_MessageReceived);
(Application.Current as App).MessageBroker.MessageReceived += new MessageReceivedEventHandler(MessageBroker_SpecialMessageReceived);

Это то, что у меня сейчас, но всегда выдает ошибку при запуске:

' Initialize the Message Broker Events
AddHandler TryCast(Application.Current, App).MessageBroker.MessageReceived, AddressOf MessageBroker_MessageReceived
AddHandler TryCast(Application.Current, App).MessageBroker.MessageReceived, AddressOf MessageBroker_SpecialMessageReceived

Есть ли что-то, что я делаю неправильно?

Вот остаток моего кода:

Partial Public Class MainWindow
Inherits Window

Public Sub New()
    InitializeComponent()

    ' Initialize the Message Broker Events
    'AddHandler TryCast(Application.Current, App).MessageBroker.MessageReceived, AddressOf MessageBroker_MessageReceived
    'AddHandler TryCast(Application.Current, App).MessageBroker.MessageReceived, AddressOf MessageBroker_SpecialMessageReceived

    TryCast(Application.Current, App).MessageBroker.MessageReceived += New MessageReceivedEventHandler(MessageBroker_MessageReceived)
    TryCast(Application.Current, App).MessageBroker.MessageReceived += New MessageReceivedEventHandler(MessageBroker_SpecialMessageReceived)

End Sub

Private Sub MessageBroker_MessageReceived(ByVal sender As Object, ByVal e As MessageBrokerEventArgs)
    ' Use this event to receive all messages
    Select Case e.MessageName.ToLower()
        Case "message1"
            ' Do something with this message
            Exit Select
        Case "message2"
            ' Do something with this message
            Exit Select
        Case "etc."
            ' Do something with this message
            Exit Select
        Case Else

            If Not String.IsNullOrEmpty(e.MessageObject.MessageBody) Then
                MessageBox.Show(e.MessageObject.MessageBody)
            End If
            Exit Select
    End Select
End Sub

Private Sub MessageBroker_SpecialMessageReceived(ByVal sender As Object, ByVal e As MessageBrokerEventArgs)
    ' Use this event to receive any special message objects
    If TypeOf e.MessageObject Is MySpecialMessage Then
        MessageBox.Show(DirectCast(e.MessageObject, MySpecialMessage).SpecialMessage)
    End If
End Sub

Ответы [ 3 ]

3 голосов
/ 16 декабря 2011

Попробуйте:

TryCast(Application.Current, App).MessageBroker.MessageReceived += New MessageReceivedEventHandler(MessageBroker_MessageReceived)
 TryCast(Application.Current, App).MessageBroker.MessageReceived += New  MessageReceivedEventHandler(MessageBroker_SpecialMessageReceived)

Я использовал http://converter.telerik.com/, что обычно хорошо работает для меня

0 голосов
/ 16 декабря 2011

Прежде всего, код C # неверен.

// Initialize the Message Broker Events
(Application.Current as App).MessageBroker.MessageReceived +=
    new MessageReceivedEventHandler(MessageBroker_MessageReceived);

(Application.Current as App).MessageBroker.MessageReceived +=
    new MessageReceivedEventHandler(MessageBroker_SpecialMessageReceived);

так и должно быть,

// Initialize the Message Broker Events
((App)Application.Current).MessageBroker.MessageReceived +=
    new MessageReceivedEventHandler(MessageBroker_MessageReceived);

((App)Application.Current).MessageBroker.MessageReceived +=
    new MessageReceivedEventHandler(MessageBroker_SpecialMessageReceived);

и VB будет,

CType(Application.Current, App).MessageBroker.MessageReceived +=
    New MessageReceivedEventHandler(MessageBroker_MessageReceived)

CType(Application.Current, App).MessageBroker.MessageReceived +=
    New MessageReceivedEventHandler(MessageBroker_SpecialMessageReceived)

as и TryCast сначала проверьте тип экземпляра, чтобы увидеть, соответствует ли он типу приведения. Если этого не произойдет, он вернет null, и вы получите исключение NullReferenceException. Вместо этого вы должны приводить тип напрямую, используя (Type)instance или CType(instance, Type). Логично, что это не будет иметь значения, но вы все равно должны понимать разницу. :)

0 голосов
/ 16 декабря 2011

попробуйте и посмотрите, будет ли это работать

TryCast(Application.Current, App).MessageBroker.MessageReceived += New MessageReceivedEventHandler(MessageBroker_MessageReceived)
TryCast(Application.Current, App).MessageBroker.MessageReceived += New MessageReceivedEventHandler(MessageBroker_SpecialMessageReceived)
...