c# - 委托(delegate)还是反射(reflection)?

标签 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);
   }
}

现在这段代码运行良好,带有反射的东西。但我想知道,这难道不应该与委托(delegate)一起实现(甚至更好吗?)?如果是这样,我如何通过使用委托(delegate)来实现它?

最佳答案

你不能用接口(interface)代替吗:

 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
 }

关于c# - 委托(delegate)还是反射(reflection)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8163908/

相关文章:

c# - 如何使用自动增量列将集合保存为用户定义的数据类型?

c# - 抛出新异常未被 Server.GetLastError() 捕获

java - 为什么同一个 interned String 文字在此 java 代码片段中具有多个值?

c# - C# 是否有方法内部方法的概念?

c# - delegate.Invoke 是如何工作的?

c# - Foreach 不会将每个项目从 foreach 添加到 ViewModel

c# - 接受一个对象并返回另一个对象的通用委托(delegate)

c# - 如何使用 Roslyn 执行反射操作

go - 在 golang 反射 FieldByName 中忽略大小写

c# - 简单的 C# 事件参数问题