Exemplo n.º 1
0
        static void Main(string[] args)
        {
            Del del = DelMessage;

            del.Invoke("Hello Delegate");
            del = DelOtherMessage;
            del.Invoke("Another Message");
            Console.ReadLine();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var mark = new Mark();

            Del d = mark.AddNumbers;

            Console.WriteLine(d.Invoke(3, 4));

            d = mark.MultiplyNumbers;
            Console.WriteLine(d.Invoke(3, 4));

            d = mark.DoAnotherThing;
            Console.WriteLine(d.Invoke(3, 4));
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            Del d = Foo1;

            d += Foo2;
            d += Foo3;
            d += Foo3;
            d += Foo3;
            d += Foo4;
            d += (str) => { Console.WriteLine(str + "I do nothing"); };
            // d("My name is Ivan");
            //    Thread.Sleep(2000);
            //   Console.WriteLine("----------------------------------------");
            d -= Foo2;
            d -= Foo3;
            d -= Foo1;

            d?.Invoke("Ivan");
            //  d("My name is Ivan");

            foreach (Del item in d.GetInvocationList())
            {
                //  Console.WriteLine(item.Method);
                item?.Invoke("Olga");
            }
        }
Exemplo n.º 4
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            Recipe rec;

            string name  = tbName.Text;
            string descr = tbDesc.Text;

            int cookingType, temperature;


            try
            {
                cookingType = int.Parse(tbCookingType.Text);
                temperature = int.Parse(tbTemp.Text);
            }
            catch
            {
                MessageBox.Show("Data is incorrect! Try again!");
                return;
            }

            if (wIngredients.Count == 0)
            {
                MessageBox.Show("Choose and add weighted ingredients");
                return;
            }

            rec = new Recipe(name, wIngredients.ToArray(), temperature, cookingType, descr);

            del.Invoke(rec);
            Close();
        }
        public override Table Execute(Table table)
        {
            if (column.Type == DataType.StringDimension || column.Type == DataType.DateDimension)
            {
                throw new BadColumnForComputationException();
            }
            double newCellContent;

            foreach (Cell cell in column.Cells)
            {
                newCellContent = del.Invoke((double)cell.Content);
                newRows.Add(new Cell(newCellContent));
            }
            List <Column> newColumnList = new List <Column>();

            foreach (Column col in table.Columns)
            {
                Column newCol = new Column(col.Name, col.Type);
                foreach (Cell cell in col.Cells)
                {
                    newCol.AddCell(new Cell(cell.Content));
                }
                newColumnList.Add(newCol);
            }

            Table  newTable  = new Table(table.Name, table, newColumnList);
            Column newColumn = new Column("Computation", DataType.FloatFact, newRows);

            newTable.AddColumn(newColumn);
            return(newTable);
        }
Exemplo n.º 6
0
        static void Main()
        {
            int Numberonthismoment = 6;

            MyDelegate1 Del;

            Del = delegate(MyDelegate2[] a)
            {
                double sam = 0;

                foreach (var i in a)
                {
                    sam += i.Invoke();
                }

                return(sam / a.Length);
            };

            var array = new MyDelegate2[Numberonthismoment];

            for (int i = 0; i < Numberonthismoment; i++)
            {
                array[i] = AddNumber;
            }

            Console.WriteLine(Del.Invoke(array));
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            Del2 pro = (double x, int i) =>
            {
                double res1 = 1;
                for (int j = 1; j < 6; j++)
                {
                    res1 *= i * x / j;
                }
                return(res1);
            };
            Del sum = (x) =>
            {
                double res2 = 0;
                for (int i = 1; i < 6; i++)
                {
                    res2 += pro(x, i);
                }
                return(res2);
            };

            Console.Write("Write double x = ");
            double my_x;

            double.TryParse(Console.ReadLine(), out my_x);
            Console.WriteLine($"results = {sum?.Invoke(my_x)}");

            Console.ReadKey();
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            WeightedIngredient wIngredient;
            Ingredient         ingredient;

            int weight;

            try
            {
                weight = int.Parse(tbWeight.Text);
            }
            catch
            {
                MessageBox.Show("Data is incorrect! Try again!");
                return;
            }

            if ((ingredient = (Ingredient)cbIngredients.SelectedItem) == null)
            {
                MessageBox.Show("Please choose ingredient type");
                return;
            }

            wIngredient = new WeightedIngredient(ingredient, weight);

            del.Invoke(wIngredient);
            Close();
        }
        public static async Task Update(this CloudTable cloudTable, string rowKey, string responseBytes, Del updateItem, int count = 0)
        {
            try
            {
                var retrieve = TableOperation.Retrieve <Image>(rowKey, rowKey);

                var tableResult = await cloudTable.ExecuteAsync(retrieve);

                var existingImage = tableResult.Result as Image;

                updateItem.Invoke(existingImage, responseBytes);

                var mergeOperation = TableOperation.Merge(existingImage);

                await cloudTable.ExecuteAsync(mergeOperation);
            }
            catch (Exception ex)
            {
                if (count < 5)
                {
                    var r = new Random().Next(0, 5);

                    Thread.Sleep(r * 1000);

                    await Update(cloudTable, rowKey, responseBytes, updateItem, ++count);
                }
                else
                {
                    throw ex;
                }
            }
        }
 public FilterCommand(Column column,Del del)
 {
     invalidRows = new List<int>();
     foreach (Cell cell in column.Cells)
     {
         if (!del.Invoke(cell.Content)) invalidRows.Add(column.Cells.IndexOf(cell));
     }
 }
Exemplo n.º 11
0
 public FilterCommand(Column column, Del del)
 {
     invalidRows = new List <int>();
     foreach (Cell cell in column.Cells)
     {
         if (!del.Invoke(cell.Content))
         {
             invalidRows.Add(column.Cells.IndexOf(cell));
         }
     }
 }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            // Instantiate the delegate.
            Del handler = DelegateMethod2;

            Del handler2 = DelegateMethod;

            // Call the delegate.
            handler("Hello World");
            handler2.Invoke("this is through invoke: Hello World");

            Console.ReadKey();
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            //Formas de usar o delegate
            //1
            DelCalculo somar = CalculationService.Somar;

            System.Console.WriteLine(somar(10, 20));
            //2 - com o new
            DelCalculo somar2 = new DelCalculo(CalculationService.Somar);

            System.Console.WriteLine(somar2(10, 21));
            //3 com o invoke
            DelCalculo somar3 = CalculationService.Somar;

            System.Console.WriteLine(somar3.Invoke(10, 22));

            //Multi referencias com delegate
            MostrarNumeros mostrar = CalculationService.MostrarMenor;

            mostrar += CalculationService.MostrarMaior;
            mostrar += CalculationService.MostrarNumeroPar;
            mostrar += CalculationService.MostrarNumeroImpar;

            mostrar.Invoke(12, 13);

            var       cal = new CalculationService();
            DelContar c   = cal.Contar;

            c(15);

            //Call back
            Del del = new Del(CalculationService.DelegateMethod);

            CalculationService.MethodWithCallback(10, 10, del);

            ReferenciaMetodo delRefMethod = CalculationService.DelegateMethod;

            CalculationService.ChamaDelegate("Passei o metodo ChamaDelegate",
                                             "para o Delegate Referencia Metodo", delRefMethod);

            Del d1 = CalculationService.DelegateMethod;
            Del d2 = CalculationService.DelegateMethod2;
            Del d3 = CalculationService.DelegateMethod2;

            Del d4 = d1 + d2 + d3;

            System.Console.WriteLine(d2 == d3);

            d4.Invoke("Invocando metodos");
        }
Exemplo n.º 14
0
        public Del <T> GetMethodInt <T>(int ch)  where T : struct
        {
            Console.WriteLine("Enter the NumberOne::");
            T numone = (T)Convert.ChangeType((object)(Console.ReadLine()), typeof(T));

            Console.WriteLine("Enter the NumberTwo::");
            T       numtwo = (T)Convert.ChangeType((object)(Console.ReadLine()), typeof(T));
            T       result = default(T);
            Class1  c      = this;
            Del <T> deleg  = null;

            switch (ch)
            {
            case 1:
                deleg  = c.Addition <T>;
                result = deleg.Invoke(numone, numtwo);
                break;

            case 2: deleg = c.Substraction <T>;
                result    = deleg.Invoke(numone, numtwo);
                break;

            case 3: deleg = c.Division <T>;
                result    = deleg.Invoke(numone, numtwo);
                break;

            case 4: deleg = c.Multiplication <T>;
                result    = deleg.Invoke(numone, numtwo);
                break;

            default:
                Console.WriteLine("Invalid entry");
                break;
            }
            Console.WriteLine("Result is:: " + result);
            return(deleg);
        }
Exemplo n.º 15
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            IngredientType ingredientType;
            string         name;

            name = tbName.Text;

            if (rbIndependentType.Checked)
            {
                ingredientType = new IndependentType(name);
            }
            else if (rbCookingDepType.Checked)
            {
                int cookingType;
                int additionalCalories;

                try
                {
                    cookingType        = int.Parse(tbCookingType.Text);
                    additionalCalories = int.Parse(tbAdditional.Text);
                }
                catch
                {
                    MessageBox.Show("Data is incorrect! Try again!");
                    return;
                }

                ingredientType = new CookingDependentType(name, additionalCalories, cookingType);
            }
            else
            {
                int additionalPerTenDegrees;

                try
                {
                    additionalPerTenDegrees = int.Parse(tbAdditional.Text);
                }
                catch
                {
                    MessageBox.Show("Data is incorrect! Try again!");
                    return;
                }

                ingredientType = new TemperatureDependentType(name, additionalPerTenDegrees);
            }

            del.Invoke(ingredientType);
            Close();
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            Console.Write("Введiть точнiсть: ");
            int n    = int.Parse(Console.ReadLine());
            Del del1 = new Del(Type1);

            del1.Invoke(n);
            Del del2 = new Del(Type2);

            del2.Invoke(n);
            Del del3 = new Del(Type3);

            del3.Invoke(n);
            Console.ReadKey();
        }
Exemplo n.º 17
0
        //method
        private async void NumPinClink(string v)
        {
            if (countClick < 6)
            {
                numPin     += v.ToString();
                countClick += 1;
                switch (countClick)
                {
                case 1: BGColor1 = "Black"; break;

                case 2: BGColor2 = "Black"; break;

                case 3: BGColor3 = "Black"; break;

                case 4: BGColor4 = "Black"; break;

                case 5: BGColor5 = "Black"; break;

                case 6: BGColor6 = "Black"; break;
                }


                if (countClick == 6) //check OTP
                {
                    StartLoader();
                    bool isOTPcorrect = await Services.CheckOTP(App.User.ID, numPin);

                    StopLoader();

                    if (isOTPcorrect)
                    {
                        OnOTPCorrected?.Invoke();
                    }
                    else if (isOTPcorrect == false)
                    {
                        Vibration.Vibrate();
                        await Application.Current.MainPage.DisplayAlert("Wrong Pin", "Enter again", "OK");

                        Reset();
                        return;
                    }
                }
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Error", "OK");
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            Del del = null;
            int x   = int.Parse(Console.ReadLine());

            del += x =>
            {
                double sum    = 0;
                double proizv = 1;
                for (int i = 1; i <= 5; i++)
                {
                    for (int j = 1; j <= 5; j++)
                    {
                        proizv *= i * x / j;
                    }
                    sum   += proizv;
                    proizv = 1;
                }
                return(sum);
            };
            Console.WriteLine(del?.Invoke(x));
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            Console.Write("Enter the accuracy: ");
            int num     = int.Parse(Console.ReadLine());
            var one     = 1.0;
            var delenie = 1.0 / 2.0;

            Console.WriteLine("1) 1 + 1/2 + 1/4 + 1/8 + 1/16 + ...\n" +
                              "2) 1 + 1/2! + 1/3! + 1/4! + 1/5! + ...\n" +
                              "3) 1 + 1/2 - 1/4 + 1/8 - 1/16 + ...\n");
            Del del1 = FirstSum;

            Console.WriteLine($"Результат першої формули: {del1?.Invoke(one, delenie, num)}");
            Del del2 = SecondSum;

            Console.WriteLine($"Результат другої формули: {del2?.Invoke(one, delenie, num)}");
            Del del3 = ThirdSum;

            Console.WriteLine($"Результат третьої формули: {del3?.Invoke(one, delenie, num)}");
            del3.Invoke(one, delenie, num);
            Console.ReadKey();
        }
Exemplo n.º 20
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            Ingredient     ingredient;
            IngredientType ingredientType;
            string         name;
            float          proteins, fats, carbs, vitamins, minerals;

            name = tbName.Text;
            try
            {
                proteins = float.Parse(tbProteins.Text);
                fats     = float.Parse(tbFats.Text);
                carbs    = float.Parse(tbCarbs.Text);
                vitamins = float.Parse(tbVitamins.Text);
                minerals = float.Parse(tbMinerals.Text);
            }
            catch
            {
                MessageBox.Show("Data is incorrect! Try again!");
                return;
            }

            if ((ingredientType = (IngredientType)cbIngType.SelectedItem) == null)
            {
                MessageBox.Show("Please choose ingredient type");
                return;
            }



            ingredient = new Ingredient(name, ingredientType, proteins, fats, carbs, vitamins, minerals);



            del.Invoke(ingredient);
            Close();
        }
Exemplo n.º 21
0
    public void Move()
    {
        // SetGridInfo();
        Vector3 direction = _appleFound ? GetMoveDirectionToApple() :  CheckFreeSpaceExeptItself();

        Debug.Log("_headPosition = " + _headPosition + $" - {direction}");
        Vector3 newPOs = _headPosition += direction;

        _oldPosition = _headPosition;

        Debug.Log("_headPosition = " + _headPosition + $" - {direction} + {newPOs}");

        Del(SnakeBody[0], newPOs);
        //_headPosition = newPOs;
        LookForward(_headPosition, direction);

        for (int i = 1; i < SnakeBody.Count; i++)
        {
            _oldPosition = SnakeBody[i - 1].position;
            Del?.Invoke(SnakeBody[i], _oldPosition);
        }

        Snake._lastMove = Time.time;
    }
Exemplo n.º 22
0
 public override void Shot(Del del)
 {
     Console.WriteLine("Стреляет артилллерийская пушка");
     del.Invoke();
 }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
#if de0 //Func<>,Action<>和自定义delegate;
/*
 * 预定义委托,Func<t>有返回值,Action无返回值
 */
            Cal caler1 = new Cal();

            Del del1  = new Del(caler1.Add);
            Del del2  = new Del(caler1.Sub);
            Del del3  = new Del(caler1.Mul);
            Del del4  = new Del(caler1.Div);
            Del del5  = new Del(caler1.Div);
            Del del41 = calr1.Div;
            //Del del42 = delegate (int x, int y) { return x / y; };//匿名方法
            //Del del43 = (int x, int y) =>{ return x / y; }; //lambda表达式
            //Del del44 =  (x,y) => { return x / y; };//lambda表达式
            //Del del45 = (x, y) => x / y; //lambda表达式
            int a = 8, b = 3, c = 0;
            c = del1.Invoke(a, b);
            Console.WriteLine(c);
            c = del1(a, b);
            Console.WriteLine(c);

            Thread.Sleep(1500);

            Action       action = new Action(caler1.Report);
            Action <int> action0 = new Action <int> (caler1.Report);
            action.Invoke();
            action();
            action0.Invoke(10086);
            action0(10086 + 1);

            Thread.Sleep(1500);

            Func <int, int, int> func1 = new Func <int, int, int> (caler1.Add);
            Func <int, int, int> func2 = new Func <int, int, int> (caler1.Sub);
            int x = 100;
            int y = 200;
            int z = x;
            z = func1.Invoke(x, y);
            Console.WriteLine(z);
            z = func2.Invoke(x, y);
            Console.WriteLine(z);
            z = func1(x, y);
            Console.WriteLine(z);
            z = func2(x, y);
            Console.WriteLine(z);

            Type t = typeof(Del);

            Console.WriteLine("the name of t: {0}", t.Name);
            Console.WriteLine("t is a class: {0}", t.IsClass);
#endif

#if de1 //milk and apple,模板方法和回调方法;
            WrapFcatory      wf    = new WrapFcatory();
            ProductFactory   pf    = new ProductFactory();
            Logger           lgr1  = new Logger();
            Func <Product>   func1 = new Func <Product>(pf.MakeMilk);
            Func <Product>   func2 = new Func <Product>(pf.MakeApple);
            Action <Product> act1  = new Action <Product>(lgr1.Log);

            Box box1 = wf.WrapProduct(func1, act1);
            Box box2 = wf.WrapProduct(func2, act1);

            Console.WriteLine(box1.product.Name);
            Console.WriteLine(box2.product.Name);
#endif

#if de2 //委托高级
            Student stu1 = new Student()
            {
                ID = 1, cc = ConsoleColor.Green
            };
            Student stu2 = new Student()
            {
                ID = 2, cc = ConsoleColor.Yellow
            };
            Student stu3 = new Student()
            {
                ID = 3, cc = ConsoleColor.Red
            };
            //stu1.DoHomework();
            //stu2.DoHomework();
            //stu3.DoHomework();

            Action dh1 = new Action(stu1.DoHomework);
            Action dh2 = new Action(stu2.DoHomework);
            Action dh3 = new Action(stu3.DoHomework);

            //dh1.BeginInvoke(null,null);
            //dh2.BeginInvoke(null, null);
            //dh3.BeginInvoke(null, null);

            Thread th1 = new Thread(new ThreadStart(dh1.Invoke));
            Thread th2 = new Thread(new ThreadStart(dh2.Invoke));
            Thread th3 = new Thread(new ThreadStart(dh3.Invoke));

            th1.Start();
            th2.Start();
            th3.Start();

            for (int i = 0; i < 15; i++)
            {
                Thread.Sleep(500);
                Console.WriteLine("tick {0}", i);
                Console.ForegroundColor = ConsoleColor.Magenta;
            }
#endif
        }
Exemplo n.º 24
0
 public override void Shot(Del del)
 {
     Console.WriteLine("Стреляет танковая пушка");
     del.Invoke();
 }
Exemplo n.º 25
0
 private void CtrlBtnAdd_Click(object sender, EventArgs e)
 {
     Del?.Invoke(CtrlTBName.Text);
     Close();
 }