将处理事件处理的代码从VB.NET转换为处理事件处理的C#

时间:2018-03-28 15:24:28

标签: c# vb.net events

我正在尝试了解C#中的事件 我想将代码从VB.NET转换为C#,但我不能成功 能否帮助我将以下代码从VB.NET转换为C#? 我将非常感谢你的帮助。

Module Module1

    Class PersonClass

        Public Event nameChanged(ByVal aName As String)

        Public _Name As String
        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(ByVal value As String)
                _Name = value

                RaiseEvent nameChanged(value)
            End Set
        End Property
    End Class

    Dim WithEvents p As PersonClass

    Sub Main()

        p = New PersonClass

        p.Name = "George"
        Console.ReadLine()
    End Sub

    Sub p_nameChanged(ByVal aName As String) Handles p.nameChanged
        Console.WriteLine("{0} name changed to : {1}", Date.Now.ToString("dd-MM-yy hh:mm:ss"), aName)
    End Sub
End Module

1 个答案:

答案 0 :(得分:0)

理解C#代表和事件的链接将有助于回答任何问题。

这是为VB代码建模的代码:

using System;

// C# events start with declaring a delegate
public delegate void PersonNameChangeEvent(string oldName, string newName);

public class Person
{
    // I noticed an oddity in the VB code, in that the data member was
    // public.  It should be private, especially since there is a property
    // handler for it
    private string name;
    public string Name
    {
        get { return name;}
        set
        {
            string old = name;
            name = value;

            PersonNameChangeEvent notifyEvent = OnNameChange;
            if (null == OnNameChange)
               return;

            notifyEvent(old, name);
        }
    }

    // a delegate instance is a class member
    public event PersonNameChangeEvent OnNameChange;    
}


public static class Test
{
    public static void Main(string[] args)
    {
         Person p = new Person();

         // assign a method by using of a lamda expression to the event/delegate
         // this expression will get called in the setter of Person.Name....
         // see notifyEvent(old, name)
         p.OnNameChange += ((o, n) => { Console.WriteLine(string.Format("Person '{0}' changed to '{1}'", o, n));  } );

         p.Name = "Bob";
         p.Name = "Joe";
    }
}

不确定您想要什么解释。请问,我会尽力回答。