Example #1
0
        public static void DelegateExample()
        {
            Calculator calculator = new Calculator();

            MyDelegate1 func1 = calculator.Calc;

            Console.WriteLine("Call the delegate func1 {0} + {1} = {2}", 100, 200, func1(100, 200));

            MyDelegate1 func2 = new MyDelegate1(calculator.Calc);

            Console.WriteLine("Call the delegate func2 {0} + {1} = {2}", 500, 600, func2(500, 600));

            MyDelegate1 func3 = (x, y) => x * y;

            Console.WriteLine("Call the delegate func3 {0} * {1} = {2}", 12, 13, func3(12, 13));   // anonymouse delegate

            MyDelegate1 func4 = (x, y) => { int a = x * y; return(a + 100); };

            Console.WriteLine("Call the delegate func4 {0} * {1} + 100 = {2}", 12, 13, func3(12, 13));   // anonymouse delegate


            MyDelegate2 func5 = (x) => { Console.WriteLine("My name is {0}", x); };

            func5("Brenda Hamilton");
        }
Example #2
0
        static void Main(string[] args)
        {
            int    a = 2;
            int    b = 3;
            double c = 0;

            MyDelegate1 Sum  = (int par1, int par2) => { return(par1 + par2); };
            MyDelegate1 Sub  = (int par1, int par2) => { return(par1 - par2); };
            MyDelegate1 Mult = (int par1, int par2) => { return(par1 * par2); };
            MyDelegate2 Div  = (int par1, int par2, out double res) =>
            {
                if (par2 != 0)
                {
                    res = ((double)par1 / (double)par2);
                    return(true);
                }
                else
                {
                    res = 0;
                    return(false);
                }
            };

            Console.WriteLine(Sum(a, b));
            Console.WriteLine(Sub(a, b));
            Console.WriteLine(Mult(a, b));
            if (Div(a, b, out c))
            {
                Console.WriteLine(c);
            }

            Console.ReadKey();
        }
Example #3
0
        static void Main(string[] args)
        {
            CustomerManager customerManager = new CustomerManager();
            //customerManager.SendMessage();
            //customerManager.ShowAlert();


            MyDelegate myDelegate = customerManager.SendMessage;

            myDelegate += customerManager.ShowAlert;

            myDelegate -= customerManager.SendMessage;

            MyDelegate1 myDelegate1 = customerManager.SendMessage1;

            myDelegate1 += customerManager.ShowAlert1;

            Matematik   matematik   = new Matematik();
            MyDelegate2 myDelegate2 = matematik.Topla;

            myDelegate2 += matematik.Carp;

            var result = myDelegate2(2, 3);

            Console.WriteLine(result);

            myDelegate1("Hello");

            myDelegate();

            Console.ReadLine();
        }
Example #4
0
        public static void Demo()
        {
            // delegate = type safe function pointer, immutable

            // expression lambda - (input-params) => expression
            MyDelegate1 productIsEven = (x, y) => x * y % 2 == 0;

            Console.WriteLine(productIsEven(3, 4));
            Console.WriteLine(productIsEven(3, 5));

            // statement lambda - (input-params) => {statement; }
            MyDelegate2 greetings = n => { Console.WriteLine("Hello " + n); };

            greetings("Guido");
            greetings.Invoke("Raymond");

            // multicast delegate
            greetings += new MyDelegate2(Hiya);
            greetings("Alex");

            // multicast with non-void return type
            Func <int> func = delegate { return(1); };

            func += delegate { return(2); };
            foreach (Func <int> run in func.GetInvocationList()) // can't use var?
            {
                Console.WriteLine(run());
            }

            // generic delegate
            Func <int, int, bool> productDivByThree = (x, y) => x * y % 3 == 0;

            Console.WriteLine(productDivByThree(4, 6));
        }
Example #5
0

        
        //Question 2 Continued:
        private void Button_Q2_Click(object sender, EventArgs e)
        {
            MyDelegate1 d1;

            d1 = new MyDelegate1(stringInStrings);
            rchtxtbxQ2.Clear();
            rchtxtbxQ2.AppendText(d1(listOfStrings, txtbxQ2.Text).ToString());
        }
Example #7
0

        
        static void F(MyDelegate1 d)
        {
            var collection = Enumerable.Range(1, 10);

            foreach (var item in collection)
            {
                Console.WriteLine(d(item));
            }
        }
        static void Main(string[] args)
        {
            MyDelegate1 myDelegate1 = new MyDelegate1(MyMethod1);
            MyDelegate1 myDelegate2 = MyMethod2;

            MyDelegate1 mydel  = myDelegate2 + myDelegate1;//concat.
            var         invoke = mydel.Invoke(5, "Han");
            var         my1    = myDelegate1.Invoke(2, "l");
            var         my2    = myDelegate2.Invoke(2, "l");
        }
Example #10
0
        static void Main(string[] args)
        {
            MyDelegate1 myDelegate1 = new MyDelegate1(Method1);
            MyDelegate2 myDelegate2 = myDelegate1.Invoke();

            myDelegate2.Invoke();

            //Delay
            Console.ReadKey();
        }
Example #11
0
        static void Main(string[] args)
        {
            MyDelegate del = myclass1.mydata1;

            del.Invoke(23);

            MyDelegate1 del1 = Myclass2.mydata2;

            del1.Invoke("ramya");
        }
Example #12
0
        public void TypeExtensions__Test()
        {
            // Arrange
            MyDelegate1 d = (int a) => { return(true); };

            // Act
            var actual = d.GetType().GetFixedDeclaringType();

            // Assert
            Assert.AreEqual(this.GetType(), actual);
        }
        public Form1()
        {
            InitializeComponent();
            PopulateStudents();

            /*
             * 1.	Use a .Net delegate type to create a delegate object and assign it to
             * reference* an anonymous method that returns true when the
             * first parameter is greater than twice the second parameter.
             */

            d1 = delegate(int x, int y)
            {
                if (x > (2 * y))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            };

            /*
             * 2.	Same question as Q1, but this time replace the anonymous method
             *  with a lambda expression.Write code that invokes the delegate
             *  object created in Q1. Pass to it any values you choose, and display
             *  result.
             */

            d1 = (x, y) => x % 2 == 0 && y % 2 != 0;

            /*
             * 3.	Use a .Net  delegate type to create a delegate object to reference a
             * lambda expression that takes 2 ints and returns a double. The expression
             * is to return the square root of the first parameter times the log of the
             * second parameter.
             *
             */
            d2 = (x, y) => (Math.Sqrt(x)) * (Math.Log(y));

            /*
             *
             * 5. Using one of the class List<T> method, Write a method to get all the
             * students, from the students list, whose first name and last nam (both),
             * contain the character e.
             *
             *
             * 9.	Write code to serialize and deserialze the list of student using
             * BinaryFormatter
             *
             */
        }
Example #14
0
        static void Main(string[] args)
        {
            MyDelegate md = delegate(int val)
            {
                Console.WriteLine("Inside Anonymous method. Value: {0}", val);
            };

            md(20);
            MyDelegate1 md1 = delegate() { Console.WriteLine("From AnnonMethod "); };

            md1();
        }
Example #15
0
 public void ExClose()
 {
     if (this.InvokeRequired)
     {
         MyDelegate1 d = new MyDelegate1(Close);
         Invoke(d);
     }
     else
     {
         Close();
     }
 }
        public Form1()
        {
            InitializeComponent();
            //create a delegate object d1
            d1 = new MyDelegate1(Add);
            d2 = new MyDelegate2(FirstOddPositive);
            d3 = new MyDelegate2(minMax);

            //let d4 reference an anonymous method
            d4 = delegate(double a, double b)
            {
                return(a * b);
            };
            d5 = delegate(int[] a)
            {
                int value   = 0;
                int counter = 0;
                for (int i = 0; i < a.Length; i++)
                {
                    if (a[i] > 0 && a[i] % 2 == 0)
                    {
                        value += a[i];
                        counter++;
                    }
                }
                return(value / counter);
            };

            d6 = delegate(int nu)
            {
                if (nu > 0 && nu % 2 == 1)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            };

            d7 = delegate(int mu)
            {
                if (mu >= 50 && mu <= 100)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            };
        }
Example #17
0
    void Start()
    {
        // assigne a new delegate and assign the expression at the same time
        MyDelegate mydelegateTest = () => Debug.Log("hello from lamp.");

        // call the new delegate
        mydelegateTest();

        MyDelegate1 mydelegateTest1 = (x) => x * x;
        int         y = mydelegateTest1(5);

        Debug.Log(y);
    }
Example #18
0
        static void Main(string[] args)
        {
            //MyDelegate1 method1 = delegate() {Console.WriteLine("Hello world"); };//匿名方法
            //Lambda表达式简化 =>读作goes to,放在参数和方法体之间
            MyDelegate1 method1 = () => Console.WriteLine("Hello world");//匿名方法

            method1();
            //MyDelegate2 method2 = delegate(int x, int y) { return x + y; };
            MyDelegate2 method2 = (x, y) => x + y;;

            Console.WriteLine(method2(2, 4));
            Console.ReadLine();
        }
Example #19
0
        static void Main(string[] args)
        {
            int X = 1;
            MyDelegate <int> myDelegate = (ref int x) =>
            {
                x++;
            };                                                //给委托赋值
            MyDelegate1 <decimal> myDelegate1 = x => x + 100; //给委托赋值

            myDelegate(ref X);
            Console.WriteLine(X.ToString());//执行委托
            Console.WriteLine(myDelegate1(X).ToString());
            Console.ReadKey();
        }
Example #20
0
        public static void Main0(string[] args)
        {
            // 匿名方法:匿名方法不能直接在类中定义,而是在给委托变量赋值时,需要赋值一个方法,此时可以“现做现卖”,定义一个匿名方法给该委托
            //无参数、无返回值的匿名方法
            MyDelegate md = delegate() {
                Console.WriteLine("Hello,World!");
            };

            //无参数、无返回值的 lambda(λ) 表达式
            md += () => {
                Console.WriteLine("lambda!");
            };
            md();

            //有参数、无返回值的匿名方法
            MyDelegate1 md1 = delegate(string msg) {
                Console.WriteLine(msg);
            };

            md1("Hello,World!2");
            //有参数、无返回值的 lambda 表达式:lambda 表达式不需要表明数据类型,因为委托已经限定了参数的数据类型
            MyDelegate1 md2 = msg => {
                Console.WriteLine(msg);
            };

            md2("hello,Lambda!");

            //有参数、有返回值的匿名方法
            AddDelegate add = delegate(int n1, int n2, int n3) {
                return(n1 + n2 + n3);
            };

            Console.WriteLine(add(10, 20, 30));
            //有参数、有返回值的 lambda 表达式
            AddDelegate add1 = (n1, n2, n3) => {
                return(n1 + n2 + n3);
            };

            Console.WriteLine(add1(1, 2, 3) + "lambda!");

            AddDelegate1 add2 = (arr) => {
                for (int i = 0; i < arr.Length; i++)
                {
                    Console.WriteLine(arr[i]);
                }
                return(arr.Sum());
            };

            Console.WriteLine(add2(3, 4, 5) + " lambda!!");
        }
Example #21
0
 public Delegates()
 {
     this.myDelegate = this.MyDelegateInstance;
     //Anonymous function (method)
     this.myDelegate = delegate(string param1) { };
     //Lambda expressions
     this.myDelegate = (string param1) => Console.WriteLine();
     MyDelegate2 myDelegate2  = () => 1;
     MyDelegate2 myDelegate21 = () =>
     {
         return(1);
     };
     Func1 <int, Delegates <string>, string> a = (age, delegatesInstance) => delegatesInstance(1);
     string result = a(1, (myInt) => "");
     Func1 <int, int, string> b;
     //MyDelegate3
     MyDelegate4 myd4 =
 }
Example #22
0
        public delegate bool MyDelegate2(int value); //Declare the delegate MyDelegate2 - signature:{ "Method name": MyDelegate2,  "parameterlist": (int), "return-type": bool}
   

        static void Main(string[] args)
        {
            MyDelegate1 myDelegate1 = new MyDelegate1(CallBack1); //associate the delegate myDelegate1 with the method CallBack1()
            myDelegate1 += CallBack1;
            myDelegate1();                                        //Invoke the method CallBack1 through the delegate myDelegate1

            MyDelegate2 myDelegate2 = CallBack2;                  //Implicit instantiation of the delegate, just assign the reference to the method
            myDelegate2(2);

            myDelegate2 = CallBack3;                              //Assigns the delegate myDelegate2 to a new method CallBack3 (with the same signature)
            myDelegate2(3);


            myDelegate2 = delegate                                //Assigns the delegate myDelegate2 to a new anonymous method
            {
                Console.WriteLine("Calling an anonymous method");
                return true;
            };
            myDelegate2(4);
        }
Example #23
0
        static void Main(string[] args)
        {
            MyDelegate myDelegate = delegate(int x) { return(x * 2); }; //lambda method

            myDelegate = x => { Console.WriteLine("lambda operator");
                                return(x * 2); }; //lambda operator

            //myDelegate = x => x * 2; //lambda operator(short form)

            int res = myDelegate(4);

            Sum(4, x => x * 2);
            //Console.WriteLine(res);


            MyDelegate1 myd1 = new MyDelegate1(Method1);
            MyDelegate2 myd2 = myd1();

            myd2();
        }
        static void Main(string[] args)
        {
            int n = new Random().Next(10000, 100000);

            int[] array = new int[10];

            for (int i = 0; i < array.Length; i++)
            {
                array[i] = new Random().Next(10, 100);
            }

            MyDelegate1 delegate1 = new MyDelegate1(Foo1);
            MyDelegate2 delegate2 = new MyDelegate2(Foo2);

            delegate2.Invoke(delegate1.Invoke(n));
            Console.WriteLine();
            delegate2.Invoke(array);
            Console.WriteLine();

            Console.WriteLine($"Target: {delegate1.Target}; Method: {delegate1.Method}");
            Console.WriteLine($"Target: {delegate2.Target}; Method: {delegate2.Method}");
        }
Example #25
0
        public static void Main(string[] args)
        {
            // **************************************************
            MyDelegate1 myDelegate1 = delegate
            {
                System.Console.WriteLine("Hello, World!");
            };

            myDelegate1();
            // **************************************************

            // **************************************************
            MyDelegate2 myDelegate2 = delegate(string text)
            {
                System.Console.WriteLine(text);
            };

            myDelegate2("Hello, World!");
            // **************************************************

            // **************************************************
            MyDelegate3 myDelegate3 = delegate(string text)
            {
                string strReturnValue = text.ToUpper();

                System.Console.WriteLine(text);

                return(strReturnValue);
            };

            string strResult = myDelegate3("Hello, World!");

            System.Console.WriteLine("Result: {0}", strResult);
            // **************************************************

            System.Console.Write("Press [ENTER] To Exit...");
            System.Console.ReadLine();
        }
Example #26
0
        /// <summary>
        /// 原委托调用示例
        /// </summary>
        /// <param name="student1"></param>
        /// <param name="student2"></param>
        private static void ScoreDelegate(Student student1, Student student2)
        {
            Console.WriteLine("-----------------原委托的调用start!---------------");
            Console.WriteLine("-----------------1---------------");
            //1.实例化 不带返回值 不带参数 的委托
            //MyDelegate1 my = new AutoDelegateDemo().SayHello;//单方法执行
            MyDelegate1 my = null; //可执行多个方法

            my += new AutoDelegateDemo().SayHello;
            my += new AutoDelegateDemo().SayHellolilei;
            my.Invoke();//执行无参数无返回值的委托SayHello方法
            Console.WriteLine("-----------------2---------------");

            //2.实例化 不带返回值 带参数 的委托
            //MyDelegate2 f2 = new MyDelegate2(new AutoDelegateDemo().SayHello);/单方法执行
            MyDelegate2 f2 = null;

            f2 += new MyDelegate2(new AutoDelegateDemo().SayHello);
            f2 += new MyDelegate2(new AutoDelegateDemo().LileiSayHello);
            f2(student1.Name);

            Console.WriteLine("-----------------3---------------");
            //3.实例化 带返回值 带参数 的委托
            MyDelegate3 f3 = new AutoDelegateDemo().GetReturn;

            Console.WriteLine(f3());

            Console.WriteLine("-----------------4---------------");
            //4.实例化 带返回值 带参数 的委托
            MyDelegate4 f4     = new AutoDelegateDemo().SumStuAge;
            string      result = f4(student1, student2);

            Console.WriteLine(student1.Name + "和" + student2.Name + "年龄和为:" + result);


            Console.WriteLine("-----------------原委托的调用end!---------------");
        }
Example #27
0
        static void Main(string[] args)
        {
            //MyDelegate1 d = new MyDelegate1(Sum);
            MyDelegate1 d   = Max;
            int         i   = d(5, 9);
            int         max = d(6, 98);

            MyNewDelegate nd;

            nd  = DoSomething;
            nd += DoSomethingElse;

            //nd();
            // or
            // |
            // |
            // V
            foreach (MyNewDelegate item in nd.GetInvocationList())
            {
                item();
            }

            Console.ReadLine();
        }
Example #28
0
 {     //ЕСЛИ СОЗДАЕТСЯ АНОНИМНЫЙ МЕТОД, ТО нужно это ассоциировать как создание экземпляра делегата и СООБЩЕНИЯ этого метода с ним
     public static MyDelegate3 Method(MyDelegate1 myDelegate1, MyDelegate2 myDelegate2)
     { // это анонимный метод delegate { return myDelegate1.Invoke() + myDelegate2.Invoke(); };
         // это техника ПРЕДПОЛОЖЕНИЯ делагата: new MyDelegate(delegate { return myDelegate1.Invoke() + myDelegate2.Invoke(); });
         return(delegate { return myDelegate1.Invoke() + myDelegate2.Invoke(); });
     }
        public string ChangePerson(string IsHeadOffice, string EmployeeNo, string CompanyCode, string DepartmentId = "", string ShopId = "")
        {
            List <Person> person = new List <Person>();

            try
            {
                //总部获取部门人员方法
                if (IsHeadOffice == "1")
                {
                    //EMPLOYEE_MUTI_DEPARTMENT找人
                    MyDelegate2  My2       = new MyDelegate2(NewMethod2);
                    IAsyncResult My2Result = My2.BeginInvoke(DepartmentId, null, null);
                    //人员表找人
                    MyDelegate3  My3       = new MyDelegate3(GetDepartmentAllPerson);
                    IAsyncResult My3Result = My3.BeginInvoke(EmployeeNo, null, null);

                    var list1 = My2.EndInvoke(My2Result);
                    var list2 = My3.EndInvoke(My3Result);

                    person.AddRange(list1);
                    person.AddRange(list2);

                    person = person.GroupBy(c => c.No).Select(p => new Person {
                        No = p.Key, Name = p.FirstOrDefault().Name
                    }).ToList();
                }
                //片区获取部门人员的方法  1.人员表  2.权限  3.EMPLOYEE_MUTI_DEPARTMENT表(使用线程委托的方式查找)
                else
                {
                    MyDelegate1 My1 = new MyDelegate1(NewMethod);
                    MyDelegate2 My2 = new MyDelegate2(NewMethod2);


                    IAsyncResult My1Result = My1.BeginInvoke(EmployeeNo, CompanyCode, DepartmentId, null, null);
                    IAsyncResult My2Result = My2.BeginInvoke(DepartmentId, null, null);

                    //权限找人
                    var list1 = My1.EndInvoke(My1Result);
                    //EMPLOYEE_MUTI_DEPARTMENT找人
                    var list2 = My2.EndInvoke(My2Result);
                    //人员表找人
                    var data  = Convert.ToDecimal(DepartmentId);
                    var list3 = DbContext.EMPLOYEE.Where(c => c.DEPID == data && c.AVAILABLE == "1" && c.LEAVE == "0").Select(x => new Person()
                    {
                        No   = x.NO,
                        Name = x.NAME
                    }).ToList();
                    List <string> DeleteList3 = new List <string>();

                    person.AddRange(list1);
                    person.AddRange(list2);
                    person.AddRange(list3);

                    //去重
                    var list4 = person.GroupBy(c => c.No).Select(p => new Person {
                        No = p.Key, Name = p.FirstOrDefault().Name
                    }).ToList();
                    person = list4;

                    if (!string.IsNullOrEmpty(ShopId))
                    {
                        foreach (var item in person)
                        {
                            //从uivalue获取片区权限
                            var value    = DbContext.UIVALUE.Where(c => c.VALUETYPE == 4 && c.EMPLOYEENO == item.No).Select(x => x.VALUE).FirstOrDefault();
                            var ShopCode = DbContext.EMPLOYEE.Where(c => c.NO == item.No && c.AVAILABLE == "1" && c.LEAVE == "0").Select(x => x.SHOPCODE).FirstOrDefault();
                            //从人员信息表中获取门店
                            if (!string.IsNullOrEmpty(ShopCode))
                            {
                                value = value == null ? ShopCode : (value + "," + ShopCode);
                            }
                            if (string.IsNullOrEmpty(value) || !value.Contains(ShopId))
                            {
                                DeleteList3.Add(item.No);
                            }
                        }
                        foreach (var item in DeleteList3)
                        {
                            person.RemoveAll(c => c.No == item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write("修改报销人失败:" + ex.ToString() + "," + System.Reflection.MethodBase.GetCurrentMethod().Name + ",账号:");
            }

            return(Public.JsonSerializeHelper.SerializeToJson(person));
        }
Example #30
0
        static void Main(string[] args)
        {
            #region 1 - Delegar noutro método

            //cria instâncias dos delegates
            NumberChanger nc1 = new NumberChanger(Delegates.AddNum);
            //ou
            //nc1 = Delegates.AddNum;
            NumberChanger nc2 = new NumberChanger(Delegates.MultNum);

            //chama os métodos usando os delegates
            nc1(25);
            Console.WriteLine("Numero: {0}", Delegates.Num);
            nc2(5);
            Console.WriteLine("Numero: {0}", Delegates.Num);
            Console.ReadKey();

            #endregion

            #region 2 - Delegar noutro método
            Pessoa p = new Pessoa("Ola", new DateTime(2000, 12, 24));

            //cria instâncias de delegates
            MyDelegate1 nc3 = new MyDelegate1(p.GetIdade);
            MyDelegate2 nc4 = new MyDelegate2(Console.WriteLine);
            //o mesmo que
            //nc4 = Console.WriteLine;

            //chama metodos usando delegates
            int idade = nc3();
            Console.WriteLine("Idade: {0}", idade);

            idade = p.GetIdade();
            nc4("Nascimento: " + p.Nasci.ToString());
            Console.ReadKey();
            #endregion

            #region 3 - Delegates como parâmetros

            PrintString ps1 = new PrintString(Print.WriteToScreen);
            PrintString ps2 = new PrintString(Print.WriteToFile);

            Print.SendString(ps1);
            Print.SendString(ps2);

            Console.ReadKey();

            #endregion

            #region 4 - Delegates como parâmetros
            //cria delegate com callback associado
            Exec d1 = new Exec(Delegates.AddNumNum);

            //invoca metodo com callback no parametro
            int aux = Delegates.ExecSomething(12, 13, d1);

            //invoca delegate
            Print.SendString(ps1, "Resultado: " + aux.ToString());

            Console.ReadKey();
            #endregion

            #region 5 - Mulcasting Delegates

            MethodClass obj = new MethodClass();
            MyDelegate2 nc5 = new MyDelegate2(Console.WriteLine);
            MyDelegate2 m1  = obj.Method1;
            MyDelegate2 m2  = obj.Method2;
            nc5 = Console.WriteLine;

            //ou
            MyDelegate2 allMethodsDelegate = m1 + m2;
            allMethodsDelegate += nc5;

            allMethodsDelegate("-Teste-");
            //ao invocar allMethodsDelegate serão executados Method1, Method2 e WriteLine
            Console.ReadKey();
            #endregion

            #region 6 - Outros Delegates

            MethodClass.Method3(new int[] { 3, 4, 5, 6 }, Console.WriteLine);
            Console.ReadKey();

            MethodClass.Method3(new int[] { 3, 4, 5, 6 }, MethodClass.ShowOdd);
            Console.ReadKey();
            #endregion

            #region 7 - Anonymous Methods

            MyPrint print = delegate(int val) {
                Console.WriteLine("Inside Anonymous method. Value: {0}", val);
            };

            print(100);

            #endregion

            #region 8 - Eventos

            FileLogger fl      = new FileLogger(@"c:\temp\Process.log");
            MyClass    myClass = new MyClass();

            // Subscribe the Functions Logger and fl.Logger
            myClass.Log += new MyClass.LogHandler(MyClass.Logger);  //Event Handlers
            myClass.Log += new MyClass.LogHandler(fl.Logger);

            // The Event will now be triggered in the Process() Method
            myClass.Process();

            fl.Close();
            #endregion

            #region 10 - Events Handler

            Counter c = new Counter(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");
                c.Add(1);
            }
            #endregion

            #region 9 - Eventos
            // Create a new clock
            Clock theClock = new Clock();

            // Create the display and tell it to subscribe to the clock just created
            DisplayClock dc = new DisplayClock();
            dc.Subscribe(theClock);

            // Create a Log object and tell it to subscribe to the clock
            LogClock lc = new LogClock();
            lc.Subscribe(theClock);

            // Get the clock started
            theClock.Run();
            #endregion
        }
Example #31
0
        static void Main(string[] args)
        {
            //method communicated with delegate
            void TestDrive(string text)
            {
                Console.WriteLine("I'll start the engine");
                Console.WriteLine("The movement is over");
            }

            //create dispether
            Dispather ivanov = new Dispather("Ivanov", "Sergey", 29, Gender.man, 5);

            CollectionClients(ivanov);

            //create collection car
            Program my   = new Program();
            var     list = my.CollectionVehicle();

            while (true)
            {
                ivanov.thehnics = list;

                //create delegate menu
                MyDelegate1 Menu = new MyDelegate1(my.ShowMenu);

                //delegate invocation
                Menu?.Invoke();

                //menu selection
                Operation op;
                Enum.TryParse(Console.ReadLine(), out op);
                switch (op)
                {
                //Become A Client
                case Operation.BecomeAClient:
                {
                    var fulname = AddNameClient();
                    AddMyClient(ivanov, fulname.Item1, fulname.Item2);
                }
                break;

                //Show All Vehicle
                case Operation.ShowAllVehicle:
                {
                    list.Show();
                }
                break;

                //Sort By Price
                case Operation.SortByPrice:
                {
                    list.tehnics.Sort();
                    list.Show();
                }
                break;

                //Buy Car
                case Operation.BuyTechniks:
                {
                    var    fulname     = AddNameClient();
                    Client CurrentUser = null;
                    foreach (var item in ivanov.client)
                    {
                        if (item.FirstName == fulname.Item1 && item.LastName == fulname.Item2)
                        {
                            CurrentUser = item;
                        }
                        break;
                    }
                    if (CurrentUser != null)
                    {
                        CurrentUser.SayToDispather(ivanov);
                        CurrentUser.BuyCar(ivanov);
                    }
                    else
                    {
                        Client client = AddMyClient(ivanov, fulname.Item1, fulname.Item2);
                        client.SayToDispather(ivanov);
                        client.BuyCar(ivanov);
                    }
                }
                break;

                //Show Clients
                case Operation.ShowClients:
                {
                    ivanov.Showweed += Disp;
                    ivanov.ShowClients();
                }
                break;

                //Add Car
                case Operation.AddTehnics:
                {
                    list.Show();
                    Car mycar = AddMyCar();
                    list.Addtehnics(mycar);
                    Console.WriteLine($"Add car {mycar.Name}");
                    list.Show();
                }
                break;

                //Delete Car MyCollection
                case Operation.DeleteTehnics:
                {
                    list.Show();
                    Console.WriteLine("Enter name Car");
                    string  str         = Console.ReadLine();
                    Vehicle CurentCount = null;
                    foreach (var item in list.tehnics)
                    {
                        if (item.Name == str)
                        {
                            CurentCount = item;
                        }
                    }
                    list.tehnics.Remove(CurentCount);
                    list.Show();
                }
                break;

                //Take a car for a test drive
                case Operation.TetsDrive:
                {
                    list.Show();
                    Console.WriteLine("select a car");
                    string str = Console.ReadLine();
                    foreach (var item in list.tehnics)
                    {
                        if (item.Name == str)
                        {
                            Console.WriteLine(item.ToString());
                            Car myCar = new Car();
                            myCar         = item as Car;
                            myCar.Drive  += TestDrive;
                            systemPoolLog = new EventLog();
                            myCar.Drive  += ShowSystem;
                            myCar.Start();
                        }
                    }
                }
                break;

                default:
                    break;
                }
                Console.WriteLine();
            }
        }