我有一个类的方法将传递一个字符串。该方法将对该字符串执行一些操作,然后将该字符串传递给某个可以对该字符串执行其他操作的对象。委托或反思?
因此,它基本上是这样的:
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);
}
}
现在这个代码的工作好,用反射的东西。但我想知道,这不应该是可能的(甚至更好?)与代表?如果是这样,我怎么可以通过使用委托实现这一点呢?
编译器错误,使它一点点努力,以确保我们在这里回答同样的问题.. 。它会很好,如果它运行(因为它“运作良好”) –