我有一个类,其中包含一个将传递字符串的方法。该方法将对该字符串做一些事情,然后将字符串传递给某个对象,该对象可以对该字符串做其他事情。
所以它基本上看起来像这样:
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/