问题描述
这是我要为委托回调编写的代码片段之一
This is one of the code snippet I am trying to do for delegate callback
public delegate void FooCallbackType(int a, int b, int c);
class CMyClass
{
public void FunctionToCall(int a, int b, int c)
{
MessageBox.Show("I am first class");
// This is the callback
}
public void Foo()
{
FooCallbackType myDelegate = new FooCallbackType(this.FunctionToCall);
// Now you can pass that to the function
// that needs to call you back.
}
}
class CMyClassWithStaticCallback
{
public static void StaticFunctionToCall(int a, int b, int c)
{
MessageBox.Show("I am second class"); // This is the callback
}
public static void Foo()
{
FooCallbackType myDelegate = new FooCallbackType(CMyClass.StaticFunctionToCall);
}
static void Main()
{
}
}
</pre>
1.在此示例中,此行代码显示错误
FooCallbackType myDelegate =新的FooCallbackType(CMyClass.StaticFunctionToCall);
因为我认为此函数属于"CMyClassWithStaticCallback"类,而不属于"CMyClass"
所以我不明白为什么/为什么是"CMyClass.StaticFunctionToCall"
2.我应该在主要部分写什么.
因为我想查看输出以了解和比较结果.
任何帮助将不胜感激.
1.In this example this line of code is showing error
FooCallbackType myDelegate = new FooCallbackType(CMyClass.StaticFunctionToCall);
because I think this function is belong to the Class "CMyClassWithStaticCallback not the "CMyClass"
so I don''t understand why/how it is "CMyClass.StaticFunctionToCall"
2.What should I write in the Main section.
because I want to see the output to understand and comapre the result.
any help will be appreciated.
推荐答案
//anonymous method, good for C# v.2 and above:
FooCallbackType myDelegate = delegate(int a, int b, int c) {
//body of your delegate code here...
};
//same thing with lambda syntax, good with C# v > 2:
myDelegate = new FooCallbackType((int a, int b, int c) => {
//body of your delegate code here...
});
同样,您的Main
可能无法编译,您还有另一个Main
.这是因为很有可能将其用作入口点.要更改入口点,请参见项目的属性",应用程序"选项卡,启动对象".
Also, your Main
may not compile you have another Main
. This is because this is used as an entry point, most likely. To change the entry point, see you project''s Property, Application tab, "Startup object".
这篇关于委托回电的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!