委托回电 [英] Delegate Call Back

查看:60
本文介绍了委托回电的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要为委托回调编写的代码片段之一

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.

推荐答案

这就是事实:您没有提供名为CMyClassWithStaticCallback的方法.
算了,没关系!您的语法太过时了!考虑一下:

This is what it is: you did not provide method called CMyClassWithStaticCallback.

Forget it, it does not matter! Your syntax is so obsolete! Consider this:

//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.这是因为很有可能将其用作入口点.要更改入口点,请参见项目的属性",应用程序"选项卡,启动对象".

—SA



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".

—SA


这篇关于委托回电的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆