代表还是反思?

w00*_*w00 1 c# reflection delegates

我有一个类,其中的方法将传递一个字符串.该方法将对该字符串执行一些操作,然后将该字符串传递给某个对象,该对象可以使用该字符串执行其他操作.

所以它基本上是这样的:

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

现在这个代码很好用,反射的东西.但我想知道,这不应该是可能的(甚至更好吗?)与代表?如果是这样,我如何通过使用委托来实现这一点?

fae*_*ter 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
 }
Run Code Online (Sandbox Code Playgroud)