C#委托基础

介绍

C#委托基础





使用

C#委托基础





普通委托详解


        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#委托基础

上一篇:WPF图表库Live Charts


下一篇:c# 对于委托,事件,泛型的理解