码迷,mamicode.com
首页 > Windows程序 > 详细

C#委托基础

时间:2020-05-10 12:58:52      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:without   ant   param   i++   ast   sed   main   returns   img   

介绍

技术图片





使用

技术图片





普通委托详解


        static void Main(string[] args)
        {
            int x = 100;
            int y = 300;

            //Get the pointer of the function "ToStirng" and apply it to the varible getAString
            GetAString getAString = new GetAString(x.ToString);
            GetAString getAString2 = x.ToString;//2nd Way to define: same as above
            Console.WriteLine(getAString());//Usable while calling by varible "getAString"
            Console.WriteLine(getAString2());//Usable while calling by varible "getAString2"

            string str = getAString.Invoke();//2nd way to call
            string str2 = getAString2.Invoke();//2nd way to call
            Console.WriteLine(str);
            Console.WriteLine(str2);

            MethodHolder myMethod = new MethodHolder(y.ToString);
            Console.WriteLine(AnotherMethod(myMethod));
        }


        //Signature of the delegate
        delegate void VoidFuncWithOneParameter(int parameter);
        delegate int IntFuncWithOneParameter(int parameter);
        delegate int IntFuncWithTwoParameters(int parameterInt, string parameterStr);

        delegate string GetAString();//This will be treated as a class


        /*!IMPORTANT!*/
        delegate string MethodHolder();

        //delegate can be used to send a method as parameter to another method
        static string AnotherMethod(MethodHolder method)
        {
            return method();//just like a callback-function in JS
        }






Action委托详解


        static void Main(string[] args)
        {
            //Action is a delegate which points to a void method without parameters 
            Action voidMethod = Method;
            voidMethod();

            //Action<type of parameter> can  points to a void method with parameters 
            Action<int> voidMethodWithParameters = MethodWithParameters;
            voidMethodWithParameters(5);
        }

        static void Method()
        {
            Console.WriteLine("This is a method which returns nothing.");
        }

        static void MethodWithParameters(int parameter)
        {
            if (parameter > 0)
            {
                for (int i = 0; i < parameter; i++)
                {
                    Console.WriteLine("This is a void method with a parameter.");
                }
            }
            else
            {
                Console.WriteLine("Parameter should be greater than 0");
            }
        }

C#委托基础

标签:without   ant   param   i++   ast   sed   main   returns   img   

原文地址:https://www.cnblogs.com/ezhar/p/12862724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!