C#拨调callback的C#及JS同步、异步实现

代码很简单,不多进行解释,假使发生问号和指出要留言,回第一时间回复

C#代码first

    class Program {
        static void Main(string[] args) {
            MyCallback mc = new MyCallback();
            mc.Callback(new Action(success), new Action(failed));
            mc.Callback(new Action(() => {
                Console.WriteLine("无参匿名success");
            }), new Action(() => {
                Console.WriteLine("无参匿名failed");
            }));
            mc.Callback(new Action<object>(success), new Action<object>(failed));
            Console.ReadKey();//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        }

        static void success() {
            Console.WriteLine("无参success");
        }
        static void failed() {
            Console.WriteLine("无参failed");
        }

        static void success(object str) {
            Console.WriteLine((string)str);
        }
        static void failed(object str) {
            Console.WriteLine((int)str);
        }
    }

    class MyCallback {
        public void Callback(Action success, Action failed) {
            success();
            failed();//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        }

        public void Callback(Action<object> success, Action<object> failed) 
        {
            success("123");
            failed(456);
        }
    }

JS代码

    <script type="text/javascript">
        var mc = new MyCallback();
        mc.Callback(success, failed);
        console.log(222);
        function success(str) {
            console.log(str);
        }
        function failed(num) {
            console.log(num);
        }

        mc.Callback(function (str) {
            console.log(str);
        }, function (num) {
            console.log(num);//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        })
        console.log(333);
        function MyCallback() {
            this.Callback = function (success, failed) {//无参,有参 自己选择传不传参
                successDelegate = success;//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
                failedDelegate = failed;
                setTimeout('successDelegate("111")', 1000); //异步
                setTimeout('failedDelegate("444")', 4000);//异步
                //                success("123");//同步
                //                failed(456);//同步
            }
        }              
    </script>    

 

 

相关文章