2011-11-17 3 views
1

문자열을 전달할 메서드가있는 클래스가 있습니다. 이 메소드는 문자열에 대해 몇 가지 작업을 수행 한 다음 문자열을 다른 객체를 수행 할 수있는 특정 객체에 전달합니다.대의원 또는 반성?

는 그래서 기본적으로 다음과 같습니다

class Main 
{ 
    public Main() 
    { 
     strClass str = new strClass(this); 
    } 

    public function handler () 
    { 
     console.log("No string is passed yet, but this method is called from receiveData()"); 
    } 
} 

class strClass 
{ 
    object handler; 
    public strClass (handler) 
    { 
     // save the object 
     this.handler = handler; 
    } 

    public receiveData (string str) 
    { 
     // This method does some stuff with the string 
     // And it then passes it on to the supplied object (handler) which will do 
     // the rest of the processing 

     // I'm calling the "handler" method in the object which got passed in the 
     // constructor 
     Type thisType = this.handler.GetType(); 
     MethodInfo theMethod = thisType.GetMethod("handler"); 
     theMethod.Invoke(this.handler, null); 
    } 
} 

지금이 코드는 반사 물건, 좋은 작품

. 하지만 궁금 해서요, 가능하지 않아야합니까 (그리고 어쩌면 더 좋을까요?) 그렇다면 어떻게 대리자를 대신 사용하여 구현할 수 있습니까?

+3

을 .. 그것은 좋은 ("좋은 작품"이후) 도망 가면 좋을거야 –

답변

4

대리인이 더 나은 옵션입니다.

class Main 
{ 

    public Main() 
    { 
     StrClass str = new StrClass(this.Handler); 
    } 

    public void Handler () 
    { 
     //called from recieve data 
    } 
} 

class StrClass 
{ 
    readonly Action _handler; 
    public StrClass (Action callback) 
    { 
     // save the object 
     this._handler = callback; 
    } 

    public void receiveData(string str) 
    { 
     this._handler(); 
    } 
} 
+0

고마워,이 위대한 작품과 훨씬 더 나은 해결책을 내가 가진 것 같다. – w00

5

는 대신 인터페이스를 사용할 수 없습니다 : 대의원을 사용하는 것보다

interface IStringHandler { 
    void HandleString(string s); 
} 


class strClass 
{ 
     IStringHandler handler = null; 

     public strClass(IStringHandler handler) 
     { 
      this.handler = handler; 
     } 

     public void ReceiveData(string s) 
     { 
      handler.HandleString(s); 
     } 
} 


class Main : IStringHandler 
{ 
     // Your code 
} 
0

첫째, dynamic을 사용 -이 크게 (아직도 좋은 생각하지만)이 최적화되어 있습니다 : 그러나

((dynamic)handler).handler(); // but please don't use this! see below 

, 내가 대신 볼 것 Action<string> (또는 아마도 Func<string,string>)이거나 알려진 메소드가있는 인터페이스입니다.

2

이 같은 Action으로 작업을 수행 할 수 있습니다

class Main 
{ 
    public Main()  
    { 
     strClass str = new strClass(newString => 
     { 
      console.log("This string I got back: " + newString);  
     }); 
    } 
} 
class strClass 
{  
    Action<string> callback; 
    public strClass (Action<string> callback) 
    { 
     // save the action 
     this.callback = callback;  
    } 
    public receiveData (string str)  
    { 
     // Do something with the string 
     callback(str); 
    } 
} 
0

는 기본적으로, 데이터가 수신을 시작하기에 어떻게 반응하는지 당신의 StrClass 개체를 변경하고 싶습니다. 사건은 내게 들리는 것 같아.

당신이 Main 및 일반 HandlerObject에서 모두 처리하는 방법이이 같은 : 컴파일러 오류가 조금 하드 우리가 여기에 같은 질문에 대답하고 있는지 확인 할 수 있도록

class StrClass : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged = null; 
    public void OnPropertyChanged(object sender, PropertyChangedEventArgs e) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, e); 
    } 

    private string receivedString; 
    public string ReceivedString 
    { 
     get; 
     set 
     { 
      string oldStr = receivedString; 
      receivedString = value; 
      PropertyChanged(receivedString, new PropertyChangedEventArgs("ReceivedString")); 
     } 
    } 

    public void receiveData(string str) 
    { 
     //event fires here 
     ReceivedString = str; 
    } 
} 

class HandlerObject 
{ 
    public void HandlerMethod1(string s) 
    { 
     //magic 
    } 

    public void HandlerMethod2(string s) 
    { 
     //different kind of magic 
    } 
} 

class Program 
{ 
    static void HandlerMethod3(string s) 
    { 
     //another kind of magic! 
    } 

    static void Main(string[] args) 
    { 
     StrClass class1 = new StrClass(); 
     StrClass class2 = new StrClass(); 
     StrClass class3 = new StrClass(); 

     HandlerObject handler = new HandlerObject(); 

     class1.PropertyChanged += (s, e) => { handler.HandlerMethod1(s.ToString()); }; 
     class2.PropertyChanged += (s, e) => { handler.HandlerMethod2(s.ToString()); }; 
     class3.PropertyChanged += (s, e) => { HandlerMethod3(s.ToString()); }; 
    } 
} 
관련 문제