C#委托基础

2021-03-06 10:27

阅读:373

标签: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 can  points to a void method with parameters 
            Action 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 

C#委托基础

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

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


评论


亲,登录后才可以留言!