吉姆,我想学习C#代表自己。
您的代码存在的一个问题是,您尚未将代理分配给有效的处理程序。委托的签名必须与具有相同方法签名的有效处理程序相匹配。
在行:
this.MyFuncToCallFrmApp = new MyFunctionDelegate(this.MyFuncToCallFrmApp);
this.MyFuncToCallFrmApp
为代表,但它必须是一个有效的方法处理程序,而不是。
这里是你的方法处理程序如何传递:
public delegate int MyFunctionDelegate(int _some, string _args);
MyFunctionDelegate MyFuncToCallFrmApp = new MyFunctionDelegate(PrintValues);
// the method I'm mapping has a valid signature for the delegate I'm mapping to:
public void PrintValues(int some, string args)
{
Console.WriteLine(string.Format("Some = {0} & Args = {1}", some.ToString(), args));
}
希望下面的链接和示例代码将是对你有所帮助:
Delegates Tutorial
委托在C#与C或C++中的函数指针类似。使用委托允许程序员在委托对象中封装对方法的引用。然后可以将委托对象传递给可以调用引用方法的代码,而无需在编译时知道哪个方法将被调用。与C或C++中的函数指针不同,代表是面向对象的,类型安全的和安全的。 (MSDN)
public class MyClass
{
// a delegate by definition is a collection of pointers to method handlers
// I declare my delegate on this line
// PLEASE NOTE THE SIGNATURE!
public delegate void MyFunctionDelegate(int some, string args);
public MyClass() : base()
{
// instantiate the delegate (AKA create the pointer)
MyFunctionDelegate myFunctionDelegate = new MyFunctionDelegate();
// map a valid method handler (WITH THE SAME SIGNATURE) to this delegate
// I'm using "+=" operator because you can add more than one handler to a collection
myFunctionDelegate += new MyFunctionDelegate(PrintValues);
// invoke the method handler (which in this case is PrintValues() - see below)
// NOTE THE SIGNATURE OF THIS CALL
myFunctionDelegate(1, "Test");
}
// this is the handler method that I am going to map to the delegate
// AGAIN, PLEASE NOTE THE SIGNATURE
public void PrintValues(int some, string args)
{
Console.WriteLine(string.Format("Some = {0} & Args = {1}", some.ToString(), args));
}
}
您期望构造函数体中的行能够实际实现吗? – 2010-09-20 15:18:11
@JohnB:我想知道OP在试图完成什么。没有迹象表明他希望该线路做什么。如果他能解释这一点,我们可以尝试着解决该做什么。 – 2010-09-20 18:19:19
@Jon:好的,我同意你的意见。例如,也许他只是无法理解代表。我也很难理解它们。 – JohnB 2010-09-20 18:35:47