示例#1
0
        public static void TestDelegate()
        {
            //Reparem na assinatura do MathDelegate. (int(int,int)) significa que retorna int, e que tem como argumentos dois inteiros.
            //Isto será expresso na forma de (x, y) que são os dois argumentos seguidos de => e da operação.
            //Caso a operação tenha mais que duas instruções, deverá ser colocada entre chavetas. Ou seja, ((x,y) => x+y)

            var sum      = new MathDelegate((x, y) => x + y);
            var sumTotal = sum.Invoke(1, 2);

            sumTotal = sum(1, 2);
            //Agora com duas operações
            sum = new MathDelegate((x, y) =>
            {
                var temp = 12;
                temp    *= x + y;
                return(temp);
            });
            sumTotal = sum.Invoke(1, 2);
            //No entanto não podemos mudar a variável para outro delegate, mesmo que os argumentos e o tipo de retorno seja o mesmo.
            //sum = new GenericDelegate<int>((x, y) => x + y);

            //Chamar um genérico também é simples
            var newSum = new GenericDelegate <int>((x, y) => x + y);

            sumTotal = newSum(1, 2);
            var newSumPrinter = new GenericDelegate <string, int>((x, y) => (x + y).ToString());
            var sumPrint      = newSumPrinter(1, 2);


            //Vamos testar?
        }
        static void Main(string[] args)
        {
            SalDelegate deleg  = new SalDelegate(GetSalary);
            var         salary = deleg.Invoke(30, 800);

            Console.WriteLine("salary = {0}", salary);
            deleg += GetIncentives;    //referencing more than one method
            var incent = deleg.Invoke(30, 800);

            Console.WriteLine("Incentives = {0}", incent);

            //multicaste delegate
            MathDelegate mathdeleg = new MathDelegate(Add);

            mathdeleg += Subtract;
            mathdeleg += Multiply;
            mathdeleg += Divide;


            mathdeleg.Invoke(950, 95);

            Program objP = new Program();

            objP.Print = new printhandler(objP.Onprint); //Registering on print event handler with print event
            objP.show();                                 //raise the print event(defined inside the show method)

            Console.ReadKey();
        }
示例#3
0
        static void Main(string[] args)
        {
            MathDelegate del1 = new MathDelegate(Add);
            MathDelegate del2 = new MathDelegate(Subtract);
            MathDelegate del3 = new MathDelegate(Multiply);
            MathDelegate del4 = new MathDelegate(Divide);

            //del1(100, 200);
            //del1 = new MathDelegate(Subtract);
            //del1(100, 200);

            MathDelegate del5 = del1 + del2 + del3 + del4;

            del5.Invoke(200, 300);
            Console.WriteLine();
            del5 -= del2;
            del5.Invoke(200, 300);
            Console.ReadKey();
        }
示例#4
0
        static void Main(string[] args)
        {
            MathDelegate m = new MathDelegate(Add);

            m += Sub;
            m += mul;
            m += div;
            m.Invoke(950, 11);

            Console.ReadKey();
        }
示例#5
0
        static void Main(string[] args)
        {
            MathDelegate deleg = new MathDelegate(Addnum);
            var          num   = deleg.Invoke(5, 10);

            Console.WriteLine("Addition={0}", num);

            deleg += Mulnum;
            var num1 = deleg.Invoke(5, 10);

            Console.WriteLine("Multiplication={0}", num);

            deleg += Subnum;
            var num2 = deleg.Invoke(5, 10);

            Console.WriteLine("Subtraction={0}", num);

            deleg += Divnum;
            var num3 = deleg.Invoke(5, 10);

            Console.WriteLine("Division={0}", num);
        }
示例#6
0
        static void Main(string[] args)
        {
            //Multicast Delegate

            MathDelegate mathdeleg = new MathDelegate(Add);

            mathdeleg += Subtract;
            mathdeleg += Multiply;
            mathdeleg += Divide;

            mathdeleg.Invoke(950, 95);


            Program objP = new Program();

            objP.Print += new PrintHandler(objP.OnPrint); //Registering OnPrint event handler with print event

            objP.Show();                                  // raise the print event(defined inside the show method

            Console.ReadKey();
        }
示例#7
0
        static void Main(string[] args)
        {
            MathClass math = new MathClass();

            MCDelegate del = new MCDelegate(math.M1);

            del += new MCDelegate(MathClass.M2);

            del += new MCDelegate(math.M1);

            del();
            del -= new MCDelegate(math.M1);
            del();

            MathDelegate del1, del2;

            del1 = new MathDelegate(math.Add);

            del2 = new MathDelegate(MathClass.Multiply);

            //MyInovoke(del1);

            AsyncCallback mycallback = delegate(IAsyncResult ir)
            {
                long result = del1.EndInvoke(ir);

                Console.WriteLine($"The add result done async is {result}");
            };

            IAsyncResult iar = del1.BeginInvoke(111, 333, mycallback, null);

            Console.WriteLine(del2.Invoke(333, 455));


            Console.ReadLine();
        }
示例#8
0
        static void Main(string[] args)
        {
            MulticastDemo md   = new MulticastDemo();
            MathDelegate  dadd = new MathDelegate(MulticastDemo.Add);
            MathDelegate  dsub = new MathDelegate(MulticastDemo.Sub);
            MathDelegate  dmul = new MathDelegate(md.Mul);
            MathDelegate  ddiv = new MathDelegate(md.Div);
            // chaining all delegate
            MathDelegate rootd = dadd + dsub + dmul + ddiv;

            rootd = rootd - dsub - dmul - ddiv;
            rootd(12, 12);
            //  earlier path
            dsub(12, 10);
            dmul.Invoke(10, 10);

            // delegate return type
            DelegateReturn dr = new DelegateReturn(DelegateReturnDemo.MethodOne);

            dr = dr + DelegateReturnDemo.MethodTwo;
            int valueReturn = dr();

            Console.WriteLine($"Delegate Return for method Two: {DelegateReturnDemo.MethodOne()}");
            Console.WriteLine($"Delegate Return for method Two: {DelegateReturnDemo.MethodTwo()}");
            //  delegate out example
            DelegateOut delegateOut = new DelegateOut(DelegateOutDemo.MethodOne);

            delegateOut = delegateOut + DelegateOutDemo.MethodTwo;
            int returnOut = 0;

            delegateOut(out returnOut);
            Console.WriteLine($"Delegate OUT for method Two: { returnOut}");
            delegateOut -= DelegateOutDemo.MethodTwo;
            delegateOut(out returnOut);
            Console.WriteLine($"Delegate OUT for method One: { returnOut}");
        }
        static void Main(string[] args)
        {
            int x, y;

            Console.Write("Enter the Value of X and Y: ");
            x = Convert.ToInt32(Console.ReadLine());
            y = Convert.ToInt32(Console.ReadLine());
            MathDelegate objAdd = (a, b) => a + b;
            MathDelegate objSub = (a, b) => a - b;
            MathDelegate objMul = delegate(int a, int b)
            {
                return(a * b);
            };

            //Calling Add
            Console.WriteLine("Result of Adding {0} and {1} is {2}", x, y, objAdd.Invoke(x, y));
            //Calling Sub
            Console.WriteLine("Result of Subracting {0} and {1} is {2}", x, y, objSub(x, y));
            //Calling Mul
            Console.WriteLine("Result of Multiplying {0} and {1} is {2}", x, y, objMul.Invoke(x, y));

            Console.Write("Enter the n value: ");
            int        n = Convert.ToInt32(Console.ReadLine());
            int        tempVal;
            List <int> valuesList = new List <int>();

            for (int i = 0; i < n; i++)
            {
                tempVal = Convert.ToInt32(Console.ReadLine());
                valuesList.Add(tempVal);
            }

            Coll coll = new Coll(valuesList);

            //Fetch All Even Numbers
            Console.WriteLine(string.Join(", ", coll.FetchEven()));

            //Greater then the Specified Value
            Console.Write("Enter the Value to fetch the value from the List that is greater then you entered: ");
            tempVal = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(string.Join(", ", coll.FetchGreaterThen(tempVal)));

            //Access Outer Variable
            Console.Write("Enter the Value you want to Search: ");
            tempVal = Convert.ToInt32(Console.ReadLine());
            if (coll.Find(tempVal) > 0)
            {
                Console.WriteLine("Value {0} is found in the index of {1} within the List {2}", tempVal, valuesList.IndexOf(tempVal), string.Join(", ", valuesList));
            }
            else
            {
                Console.WriteLine("Value {0} is not found in the List {1}", tempVal, string.Join(", ", valuesList));
            }


            //Access Outer Variable
            Console.Write("Enter the Value you want to Search(Find All): ");
            tempVal = Convert.ToInt32(Console.ReadLine());
            //Console.WriteLine(string.Join(", ", coll.MatchWithValue(tempVal)));
            Console.WriteLine("There are totally {0} no of {1} in the List {2}", coll.MatchWithValue(tempVal).Count, tempVal, string.Join(", ", valuesList));
        }
示例#10
0
        //static void CallbackHandler(IAsyncResult ir)
        //{
        //    MathDelegate del = ir.AsyncState as MathDelegate;
        //    long result = del.EndInvoke(ir);

        //    Console.WriteLine($"The add result done async is {result}");
        //}

        static void MyInovoke(MathDelegate del)
        {
            Console.WriteLine(del.Invoke(111, 222));
        }
示例#11
0
 static void Invoke(MathDelegate del)
 {
     Console.WriteLine(del.Invoke(111, 333));
 }
示例#12
0
        static void Main(string[] args)
        {
            //Single cast Delegate explanation//
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Single Cast with Basic Explanation********");
            Console.ResetColor();
            SingleCastDelegate sobj = new SingleCastDelegate();
            AddDelegate        ad   = sobj.Add;

            ad.Invoke(100, 100);
            GreetingsMessage gd = new GreetingsMessage(SingleCastDelegate.Greetings);
            // GreetingsMessage gd = new GreetingsMessage(SingleCastDelegate.Greetings);
            string name = gd.Invoke("Limon");

            Console.WriteLine(name);

            //Multicast Basic explanation//
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with Basic Explanation********");
            Console.ResetColor();
            Multicast    obj    = new Multicast();
            MathDelegate md     = Multicast.Add;
            MathDelegate mdSub  = Multicast.Sub;
            MathDelegate mdMul  = obj.Mul;
            MathDelegate mdDiv  = obj.Div;
            MathDelegate mainMd = md + mdSub + mdMul + mdDiv;

            mainMd.Invoke(10, 10);
            mainMd -= mdSub;
            Console.WriteLine($"After removing {mdSub}");
            mainMd.Invoke(20, 50);

            //Multicast with return type//
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with return type********");
            Console.ResetColor();
            // ReturnType rt = new ReturnType();
            ReturnDelegate rd = ReturnType.Method1;

            rd += ReturnType.Method2;
            int valueGet = rd();

            Console.WriteLine("Return Value:{0}", valueGet);

            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with Out type********");
            Console.ResetColor();

            ReturnDelegateOUt rdo = ReturnType.OutMethod1;

            rdo += ReturnType.OutMethod2;
            int    IdFromOut       = -1;
            string UserNameFromOut = null;

            rdo(out IdFromOut, out UserNameFromOut);
            Console.WriteLine($"Value from Output parameter Id: {IdFromOut} Name:{UserNameFromOut}");

            //
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("******Multicast with RealLife example********");
            Console.ResetColor();
            Employee emp1 = new Employee()
            {
                ID         = 101,
                Name       = "Pranaya",
                Gender     = "Male",
                Experience = 5,
                Salary     = 10000
            };
            Employee emp2 = new Employee()
            {
                ID         = 102,
                Name       = "Priyanka",
                Gender     = "Female",
                Experience = 10,
                Salary     = 20000
            };
            Employee emp3 = new Employee()
            {
                ID         = 103,
                Name       = "Anurag",
                Experience = 15,
                Salary     = 30000
            };
            List <Employee> listEmployess = new List <Employee>()
            {
                emp1, emp2, emp3
            };

            // EligibleToPromotion eligbleDelegate = Employee.Promote;

            //Employee.PromoteEmployee(listEmployess, eligbleDelegate);
            Employee.PromoteEmployee(listEmployess, x => x.Salary >= 10000);
        }
示例#13
0
 public static float ExecuteMathFunction(float left, float right, MathDelegate toInvoke)
 {
     return(toInvoke.Invoke(left, right));
 }