2014-11-11 2 views
0

나는 프로젝트를 가지고 있는데, 여기에는 클라이언트 클래스가있다. 클라이언트 객체 생성 이벤트를 원합니다. 내가 이벤트에 대한 정보를 읽을 수 있지만 난 여전히 안개에 이벤트 을 사용하는 방법이 내 코드입니다 :이벤트를 사용하여 생성 객체

public class Client 
{ 
    public string FirstName { get; set; } 
    public string SecondName { get; set; } 
    public string DateOfBirth { get; set; } 
    public string Address { get; set; } 

    public Client(string name, string surname, string dateOfBirth, string address) 
    { 
     FirstName = name; 
     SecondName = surname; 
     DateOfBirth = name; 
     Address = address; 
    } 

    public event EventHandler NewClient; 

    public virtual void OnNewClient(object sender, EventArgs e) 
    { 
     NewClient(this, e); 
    } 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Client client = new Client(); 
     client.OnNewClient(); 

    } 


    public void CreateNewClient(string name, string surname, string dateOfBirth, string address) 
    { 
     string Name = name; 
     string Surname = surname; 
     string Date = dateOfBirth; 
     string Address = address; 

     Client client = new Client(Name, Surname,Date, Address); 
    } 
} 
+0

남자 :

// Client class only cares about itself; is completely independent public class Client { public string FirstName { get; set; } public string SecondName { get; set; } public string DateOfBirth { get; set; } public string Address { get; set; } public Client(string name, string surname, string dateOfBirth, string address) { FirstName = name; SecondName = surname; DateOfBirth = name; Address = address; } } // Client factory is responsible for creating clients class ClientFactory { // Event name should describe what happened public event EventHandler ClientCreated; public Client CreateNewClient(string name, string surname, string dateOfBirth, string address) { // no need to copy the arguments into new local variables again; arguments // are already local Client client = new Client(name, surname, dateOfBirth, address); // raise the ClientCreated event OnClientCreated(); // return the created client return client; } // provide this proctected virtual method for raising the event protected virtual void OnClientCreated(EventArgs e) { var handler = ClientCreated; if (handler != null) handler(this, e); } // provide private specialized versions for convenience (e.g. to call it without // passing an argument) private void OnClientCreated() { OnClientCreated(EventArgs.Empty); } } 

은 다음과 같이 사용합니다 :

적절한 솔루션은 아마도 다음과 같을 것이다. 어쩌면 설명을 추가하고 맞춤법 오류를 수정했을 수도 있습니다. – MichaC

+0

저는 새로운 객체가 생성되거나 새로운 객체를 만드는 이벤트를 발생 시키려고 할 때마다 이벤트를 발생 시키길 원하십니까? 이벤트가 트리거하려면 무언가가 필요합니다. 두 번째 경우가 명확하지 않습니다 (이벤트가 실행되는 것은 무엇입니까?) –

+0

클라이언트의 인스턴스를 생성하는 이벤트가 있습니다. – Vlad

답변

2

어디서 시작해야할지 모르겠다 ... 이벤트는 개체에 속하며 구독해야합니다. 그래서 당신이 만든 객체에 이벤트를 갖는 것은 실제로 에 가입해야만하기 때문에 실제로는 도움이되지 않습니다. 전에 객체가 실제로 생성됩니다 (불가능합니다). 따라서 이벤트는 CreateNewClient 메서드가있는 곳에 있어야합니다. 말하자면, 생성 된 클라이언트도 반환하는 것이 좋습니다. 그리고 그 방법은 사건을 제기해야합니다. 난 정말 당신이 실제로 달성하려는 모르겠어요

// create the client factory 
ClientFactory factory = new ClientFactory(); 

// subscribe to the event 
factory.ClientCreated += (s, e) => { 
    Console.WriteLine("Client created."); 
}; 

// create clients 
Client c1 = factory.CreateNewClient("Foo", "Bar", "Baz", "Baf"); 
Client c2 = factory.CreateNewClient("Foo", "Bar", "Baz", "Baf"); 
+0

이 코드 부분을 설명해 주시겠습니까? "handler (this, e)". espessialy "EventArgs e"를 사용하는 방법이 명확하지 않습니다. – Vlad

+0

자세한 내용은 [이 답변] (http://stackoverflow.com/a/282741/216074)을 참조하십시오. 즉, 이벤트 처리기에 대한 스레드 안전 참조를 저장 한 다음 null이 아닌 경우 해당 저장 이벤트 처리기를 호출합니다. – poke

0

즉, 이벤트,이 코드, 윌 거의 결코 일; 그 이유는 객체가 존재하지 않았기 때문이며, 이벤트는 생성 직후에 발생하기 때문입니다.

다른 말로 : 아무도 이벤트에 등록 할 기회가 없었습니다! 당신이 정말로이 동작을 원하지 경우

하는 공장을 사용하는 것이 좋습니다 :

public static class ClientFactory 
{ 
    public static event Action ClientCreated; 
    public static Client CreateClient(..) 
    { 
     Client retValue = new Client(...); 

     if (ClientCreated != null) 
      ClientCreated(); 

     return retValue; 
    } 
} 

는 이제 클라이언트가 등록을 개체하는 지속적인 이벤트가 있습니다. static이 아니므로 가장 좋은 방법은입니다. 가장 빠른 유형입니다. Factory 패턴을보다 잘 구현할 수 있습니다.

관련 문제