我有一個類的方法將傳遞一個字符串。該方法將對該字符串執行一些操作,然後將該字符串傳遞給某個可以對該字符串執行其他操作的對象。委託或反思?
因此,它基本上是這樣的:
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);
}
}
現在這個代碼的工作好,用反射的東西。但我想知道,這不應該是可能的(甚至更好?)與代表?如果是這樣,我怎麼可以通過使用委託實現這一點呢?
編譯器錯誤,使它一點點努力,以確保我們在這裏回答同樣的問題.. 。它會很好,如果它運行(因爲它「運作良好」) –