Esempio n. 1
0
 public void AddInfo(TextBox txtBox, ListBox listBox, AddDelegate addMethod, GetDelegate getMethod)
 {
     string txt = txtBox.Text;
     int addCount = 0;
     DataSet ds;
     if (txt != "")
     {
         addCount = addMethod(txt);
         if (addCount <= 0)
         {
             MsgBox("该值已存在!");
         }
     }
     else
     {
         MsgBox("不能添加空值!");
     }
     listBox.Items.Clear();
     txtBox.Text = "";
     ds = getMethod();
     for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
     {
         listBox.Items.Add(ds.Tables[0].Rows[i][0].ToString());
     }
     txtBox.Focus();
 }
Esempio n. 2
0
        //初始化加载
        private void FormServer_Load(object sender, EventArgs e)
        {
            //实例化委托对象,与委托方法关联
            AppendString = new AppendDelegate(AppendMethod);
            Addfriend = new AddDelegate(AddMethod);
            Removefriend = new RemoveDelegate(RemoveMethod);
            //获取本机IPv4地址
            List<string> listIP = getIP();
            if (listIP.Count == 0)
            {
                this.comboBoxIP.Items.Clear();
                this.comboBoxIP.Text = "未能获取IP!";
            }
            else if (listIP.Count == 1)
            {
                this.comboBoxIP.Items.Add(listIP[0]);
                this.comboBoxIP.SelectedIndex = 0;
            }
            else
            {
                foreach (string str in listIP)
                {
                    this.comboBoxIP.Items.Add(str);
                }
                this.comboBoxIP.Text = "请选择IP!";
            }
            //设置默认端口号
            textBoxServerPort.Text = "8899";

            buttonStop.Enabled = false;
        }
Esempio n. 3
0
 static void Main(string[] args)
 {
     int result;
     AddDelegate add = new AddDelegate(Add);
     Console.WriteLine("[Main] Invoking the asynchronous  Add method");
     add.BeginInvoke(6, 42, out result, new AsyncCallback(AnnounceSum), add);
     Thread.Sleep(1000);
     Console.ReadLine();
 }
        static void Main(string[] args)
        {
            int l = 3, r = 4;

            AddDelegate add = new AddDelegate(Add);
            Data d = new Data();

            IAsyncResult ar = add.BeginInvoke(l, r, new AsyncCallback(Callback), d);
            d.mre.WaitOne();

            // write result in main thread
            // alternatively, could write result in Callback
            Console.WriteLine("Result is {0} ", d.data);
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            int l = 3, r = 4;

            AddDelegate add = new AddDelegate(Add);
            IAsyncResult ar = add.BeginInvoke(l, r, null, null);

            //while (!ar.IsCompleted) Thread.Sleep(10);
            // or
            ar.AsyncWaitHandle.WaitOne();

            // write result in main thread
            // if async delegate causes an exception it will become visible when EndInvoke is called
            try
            {
                Console.WriteLine("Result is {0} ", add.EndInvoke(ar));
            }
            catch (Exception e) { Console.WriteLine(e.Message); }
        }
Esempio n. 6
0
        public void DelInfo(ListBox listBox, AddDelegate delMethod, GetDelegate getMethod)
        {
            ListItem delName = listBox.SelectedItem;
            DataSet ds;

            if (delName == null)
            {
                MsgBox("请选择要删除的项!");
            }
            else
            {
                delMethod(delName.Text);
            }

            listBox.Items.Clear();
            ds = getMethod();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                listBox.Items.Add(ds.Tables[0].Rows[i][0].ToString());
            }
        }
Esempio n. 7
0
 //使用委托类型的参数
 public static void invokeDelegate(AddDelegate del, int i, int j)
 {
     Console.WriteLine(del(i, j));
 }
 public AddChangeParametr(AddDelegate <Parameters> addDelegate, string testName)
 {
     InitializeComponent();
     DataContext = new AddChangeParametersViewModel(addDelegate, testName);
 }
Esempio n. 9
0
 //使用委托类型参数的方法
 public static void InvokeDelegate(AddDelegate addDel, int x, int y)
 {
     Console.WriteLine(addDel(x, y));
 }
Esempio n. 10
0
        static void Main(string[] args)
        {
            List <int> numbers = new List <int>()
            {
                1, 3, 5, 7, 8, 9, 11, 13, 14, 15
            };

            IEnumerable <int> largeNumber = numbers.Where(c => c > 14);

            foreach (int i in largeNumber)
            {
                Console.WriteLine("Large Number is " + i);
            }

            IEnumerable <int> results = from num in numbers
                                        where num < 3 || num > 7
                                        orderby num descending
                                        select num;

            int count =                 /*(from num in numbers
                                        *  where num < 3 || num > 7
                                        *  orderby num descending
                                        *  select num).Count();*/

                        numbers.Where(n => n < 3 || n > 10).Count();

            Console.WriteLine("Count is " + count);

            foreach (int num in results)
            {
                Console.WriteLine("number is : " + num);
            }

            string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };
            IEnumerable <IGrouping <char, string> > gQuery =
                from item in  groupingQuery
                group item by item[0];

            foreach (var item in gQuery)
            {
                //Console.WriteLine("Grouped Items are  - ");
            }
            Student.QueryHighScores(1, 90);
            Console.WriteLine("Hello World!");

            MQ app = new MQ();

            int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            var q1 = app.QueryMethod1(ref nums);

            foreach (string s in q1)
            {
                Console.WriteLine("string is - " + s);
            }

            IEnumerable <string> mq2;

            app.QueryMethod2(ref nums, out mq2);

            foreach (string s in mq2)
            {
                Console.WriteLine(s);
            }

            Student.GroupBySingleProperty();

            FileLogger file = new FileLogger("/Users/giridharreddykatha/Documents/Logs/log.txt");

            Logger.LogMessage(Severity.Error, "This is Error", "This Error is caused");

            Logger.LogMessage(Severity.Critical, "This is Critical Error", "Big  Error");


            AddDelegate ad = new AddDelegate(DelegateDemo.Add);

            ad.Invoke(10, 20);


            MulDelegate md = MulticastDelegate.Area;

            md += MulticastDelegate.Circumference;

            md.Invoke(10.2, 12);

            GreetingDelegate gd = delegate(string name)
            {
                return("Hello " + name + " A Very Good Morning!!");
            };

            Console.WriteLine(gd.Invoke("Friend"));

            GreetingDelegate g = (name) => { return("Hello " + name + " A Very Good Morning!!"); };

            Console.WriteLine(g.Invoke("Mike"));

            Console.ReadLine();
        }
Esempio n. 11
0
 public InstanceDataWeakTable()
 {
     _dict        = Activator.CreateInstance(_TableType);
     _tryGetValue = (TryGetValueDelegate)Delegate.CreateDelegate(typeof(TryGetValueDelegate), _dict, _TryGetValueMethod);
     _add         = (AddDelegate)Delegate.CreateDelegate(typeof(AddDelegate), _dict, _AddMethod);
 }
Esempio n. 12
0
        public static T AddParameter <T, P>(this T parameter, P feature, string criteria, AddDelegate <T> dlg)
            where T : IActor, new() where P : IActor
        {
            if (dlg(parameter))
            {
                Type parameterType = parameter.GetType();
                Type featureType   = feature.GetType();

                var property = parameterType.GetProperty(criteria).GetValue(parameter);

                Type propertyType = parameterType.GetProperty(criteria).PropertyType;


                MethodInfo methodCompare = propertyType.GetMethod("Add",
                                                                  BindingFlags.Instance | BindingFlags.Public,
                                                                  null,
                                                                  new Type[] { featureType },
                                                                  null);

                methodCompare.Invoke(property, new object[] { feature });
            }

            return(parameter);
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            LogDelegate ld = () =>
            {
                // UpdateDatabase();
                // WriteToEventLog();
                return(true);
            };
            bool status = ld();

            AddDelegate   ad = (a, b) => a + b;
            UpperDelegate up = word => word.ToUpper();

            Console.WriteLine(ad(1, 1));
            Console.WriteLine(up("hello"));
            // DelegatesAndEvents.WorkPerformedHandler del1 = WorkPerformed1;
            // DelegatesAndEvents.WorkPerformedHandler del2 = WorkPerformed2;

            // del1(5, WorkType.Golf);
            // del2(10, WorkType.GenerateReports);



            // Rectangle.Union(r1, r2);
            var rectangles = new[]
            {
                new Rectangle(0, 0, 20, 20),
                new Rectangle(20, 20, 60, 60),
                new Rectangle(80, 80, 20, 20),
            };

            // Console.WriteLine(rectangles.Aggregate(Rectangle.Union));


            var numbers = Enumerable.Range(1, 10);
            var words   = new[] { "one", "two", "three" };


            // Console.WriteLine(words.Aggregate("hello", (p,x) => p + "," + x));
            // Console.WriteLine("We have " + words.Count() + " elements");
            // LINQ.ShowResultList(numbers);

            // Console.WriteLine("Sum = " +
            //                   numbers.Aggregate(
            //                       (p, x) => p+x));

            // seed 1 -> p1
            // p1 2 -> p2
            // p2 3 ...
            // Console.WriteLine("Product = " +
            //                   numbers.Aggregate(1, (p, x) => p*x));

            // var integralTypes = new[] {typeof(int), typeof(short)};
            // var floatingTypes = new[] {typeof(float), typeof(double)};
            // LINQ.ShowResultList(integralTypes
            //     .Concat(floatingTypes)
            //     .Prepend(typeof(bool)));

            // 'System.Linq.Enumerable.Prepend<TSource>(System.Collections.Generic.IEnumerable<TSource>, TSource)'
            // 'ConsoleApp1.LinqDemos.ExtensionMethods.Prepend<T>(System.Collections.Generic.IEnumerable<T>, T)'

            // var numbers = new List<int> {1, 2, 3};
            // Console.WriteLine(numbers.First());
            // Console.WriteLine(numbers.First(x => x > 2));
            // Console.WriteLine(numbers.FirstOrDefault(x => x > 10));

            // Console.WriteLine(new int[]{123}.Single());
            // Console.WriteLine(new int[]{1,2,3}.SingleOrDefault()); // exception
            // Console.WriteLine(new int[]{}.SingleOrDefault()); // works on empty collection
            //
            // Console.WriteLine("Item at position 1: " + numbers.ElementAt(1));
            // Console.WriteLine("Item at position 1: " + numbers.ElementAtOrDefault(4));



            // var arr1 = new[] {1, 2, 3};
            // var arr2 = new[] {1, 2, 3};
            // Console.WriteLine(arr1 == arr2);
            // Console.WriteLine(arr1.Equals(arr2));
            //
            // Console.WriteLine(arr1.SequenceEqual(arr2));
            //
            // var list1 = new List<int>{1,2,3};
            // Console.WriteLine(arr1.SequenceEqual(list1));
            //
            //
            // var people = new Person[]
            // {
            //     new Person("Jane", "*****@*****.**"),
            //     new Person("John", "*****@*****.**"),
            //     new Person("Chris", String.Empty),
            // };
            //
            // var records = new Record[]
            // {
            //     new Record("*****@*****.**", "JaneAtFoo"),
            //     new Record("*****@*****.**", "JaneAtHome"),
            //     new Record("*****@*****.**", "John1980"),
            // };
            // foreach (var person in people)
            // {
            //     Console.WriteLine(person.Email);
            // }

            // var query = people.Join(records,
            //     person => person.Email,
            //     record => record.Mail,
            //     (person, record) => new {Name = person.Name, SkypeId = record.SkypeId}
            // );
            //
            // foreach (var item in query)
            // {
            //     Console.WriteLine(item);
            // }


            object[] values = { 1, 2.5, 3, 4.5 };
            // int[] numbers = {3, 3, 1, 2, 3, 4};
            // LINQ.ShowResultList(numbers.Skip(2).Take(1));
            // LINQ.ShowResultList(numbers.SkipWhile(i => i == 3));
            // Console.WriteLine("Are all numbers greater than 0? " +
            //                   numbers.All(x => x > 0));
            // Console.WriteLine("Are all numbers odd? " +
            //                   numbers.All(x => x % 2 == 1));
            // Console.WriteLine("Any number less than 2? " +
            //                   numbers.Any(x => x < 2));


            // LINQ.ShowResultList(FilteringSortingData.GetIntegers(values));
            IEnumerable <int>  randomNumbersEnumerable  = ProjectionOperations.GetRandomNumbers();
            string             randomNumbersString      = LINQ.DisplayListAsCsvString(randomNumbersEnumerable);
            IEnumerable <char> orderedNumbersEnumerable = randomNumbersString.OrderBy(x => x);

            // Console.WriteLine(LINQ.DisplayListAsCsvString(randomNumbersEnumerable));
            // Console.WriteLine(LINQ.DisplayListAsCsvString(randomNumbersEnumerable.OrderBy(x => x)));
            // Console.WriteLine(LINQ.DisplayListAsCsvString(randomNumbersEnumerable.OrderByDescending(x => x)));

            // string sentence = "This is a test";
            // Console.WriteLine(new string(sentence.Reverse().ToArray()));
            // string word1 = "hello";
            // string word2 = "help!";

            // LINQ.ShowResultList(word1.Distinct());

            // var lettersInBoth = word1.Intersect(word2);
            // LINQ.ShowResultList(lettersInBoth);

            // LINQ.ShowResultList(word1.Union(word2));
            // LINQ.ShowResultList(word1.Except(word2));
        }
Esempio n. 14
0
        ///Process-3
        //No method mane holo Anonymous Methods
        static void Main()
        {
            ///Process-1
            ///Traditional Delegates
            AddDelegate   addDele = add;
            SubDelegate   subDele = sub;
            CKNumDelegate ckDele  = cknum;

            Console.WriteLine(addDele(4.6, 4.4));
            subDele(4.5, 4);
            Console.WriteLine(ckDele(5));


            /*
             * ///Process-2
             * ///Generic Delegates
             * //Func<double,double,double> addFC = new Func<double, double, double> (add);
             * Func<double,double,double> addFC = add; // for add() method
             * Action<double,double> subAC = sub; // for sub() method
             * //Predicate<int> cknumPT = cknum; // for cknum() method
             * Func<int,bool> cknumPT = cknum; // for cknum() method
             *
             * Console.WriteLine(addFC(4.6,4.4));
             * subAC(4.5,4);
             * Console.WriteLine(cknumPT(5));
             */

            /*
             * ///Process-3
             * ///Generic Delegates and anonymous methods
             * // for add() method
             * Func<double, double, double> addFC = (a, b) =>
             * {
             *    return a + b;
             * };
             *
             * // for sub() method
             * Action<double, double> subAC = (a, b) =>
             * {
             *   Console.WriteLine(a-b);
             * };
             *
             * // for cknum() method
             * Predicate<int> cknumPT = n =>
             * {
             * if (n % 2 == 0) return true;
             * else return false;
             * };
             *
             *
             * // for cknum() method
             * //Func<int,bool> cknumPT = n=>
             * //{
             * //if (n % 2 == 0) return true;
             * //else return false;
             * //};
             *
             *
             * Console.WriteLine(addFC(4.6,4.4));
             * subAC(4.5,4);
             * Console.WriteLine(cknumPT(5));
             */
        }
 public void Add(AddDelegate d)
 {
     functions.Add(d.Method.Name, d);
 }
Esempio n. 16
0
 //使用委托类型的参数
 public static void invokeDelegate(AddDelegate del, int i, int j)
 {
     Console.WriteLine(del(i, j));
 }
Esempio n. 17
0
 public AddChangeTest(AddDelegate <Tests> addDelegate)
 {
     InitializeComponent();
     DataContext = new AddChangeTestViewModel(addDelegate);
 }
 static void Main(string[] args)
 {
     AddDelegate del = new AddDelegate(getSum);
     del(189, 390);
 }
Esempio n. 19
0
 public static int refDelegate(AddDelegate addRef)
 {
     return(addRef(5, 6));
 }
Esempio n. 20
0
        public void TestLambdaExpression()
        {
            AddDelegate addAnonymousMethod = (a, b) => a + b;

            Assert.Equal(7, addAnonymousMethod(3, 4));
        }
Esempio n. 21
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);
        }
Esempio n. 22
0
        public SpreadsheetViewModel(Extensions extensions, ModuleBuilder mb, int rows, int cols)
        {
            Type rowType = RowViewModelBase.Initialize(mb, cols);
            Type gt = typeof(ObservableCollection<>);
            Type cgt = gt.MakeGenericType(rowType);

            _getItem = CreateGetItemDelegate(cgt);
            _add = CreateAddDelegate(cgt, rowType);

            _rows = Activator.CreateInstance(cgt);
            _model = new SpreadsheetModel(extensions);

            for (int i = 0; i < rows; i++) {
                RowViewModelBase row = RowViewModelBase.Create(mb, this, i + 1, cols);
                _add(_rows, row);
            }
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            Console.WriteLine("枚举:");
            EnumGreetPeople("枚举", Language.Chinese);
            EnumGreetPeople("Enum", Language.English);
            Console.WriteLine();

            Console.WriteLine("委托:");
            GreetingDelegate delegate1, delegate2;

            delegate1 = ChineseGreeting;
            delegate2 = EnglishGreeting;
            GreetPeopple("委托", delegate1);
            GreetPeopple("delegate", delegate2);
            Console.WriteLine();

            Console.WriteLine("委托绑定一:");
            GreetingDelegate delegate3;

            delegate3  = ChineseGreeting;
            delegate3 += EnglishGreeting;
            GreetPeopple("binding", delegate3);
            Console.WriteLine();

            Console.WriteLine("委托绑定二:");
            delegate3("bundingtwo");
            Console.WriteLine();

            Console.WriteLine("委托解绑:");
            delegate3 -= EnglishGreeting;
            delegate3("unbunding");
            Console.WriteLine();

            Console.WriteLine("新类:");
            GreetingManage gm = new GreetingManage();

            gm.GreetPeople("gm类", ChineseGreeting);
            gm.GreetPeople("classgm", EnglishGreeting);
            Console.WriteLine();

            Console.WriteLine("委托新类:");
            GreetingManage   gm2 = new GreetingManage();
            GreetingDelegate delegate4;

            delegate4  = ChineseGreeting;
            delegate4 += EnglishGreeting;
            gm2.GreetPeople("gmclasstwo", delegate4);
            Console.WriteLine();

            Console.WriteLine("新类定义的委托:");
            GreetingManage gm3 = new GreetingManage();

            gm3.gmGreetingDelegate  = ChineseGreeting;
            gm3.gmGreetingDelegate += EnglishGreeting;
            gm3.gmGreetingDelegate("gmdelegate");
            Console.WriteLine();

            Console.WriteLine("模拟烧水过程,Observer设计模式:");
            Console.WriteLine();
            Heater  heater  = new Heater();
            Alarm   alarm   = new Alarm();
            Display display = new Display();

            heater.Boiled += alarm.MakeAlert;                                //注册方法
            heater.Boiled += (new Alarm()).MakeAlert;                        //给匿名对象注册方法
            heater.Boiled += new Heater.BoiledEventHandler(alarm.MakeAlert); //也可以这么注册
            heater.Boiled += Display.ShowMsg;                                //注册静态方法
            heater.BoilWater();                                              //烧水,会自动调用注册过对象的方法
            Console.WriteLine();

            Console.WriteLine("不使用异步调用的通常情况:");
            Console.WriteLine("Client application start");
            Thread.CurrentThread.Name = "Main Thread";
            Calculator cal    = new Calculator();
            int        result = cal.Add(6, 8);

            Console.WriteLine("Result:{0}", result);
            //做其他事情,模拟需要执行3秒钟
            for (int i = 1; i <= 3; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(i));
                Console.WriteLine("{0}:Client excute {1} second(s).", Thread.CurrentThread.Name, i);
            }
            Console.WriteLine();

            Console.WriteLine("使用异步调用:");
            Console.WriteLine("Client application started!\n");
            //Thread.CurrentThread.Name = "Main Thread";
            AddDelegate del  = new AddDelegate(cal.Add);
            string      data = "And data you want to pass";

            AsyncCallback callback    = new AsyncCallback(Calculator.OnAddComplete);
            IAsyncResult  asyncResult = del.BeginInvoke(5, 6, callback, data);  //异步调用方法

            del.EndInvoke(asyncResult);
            // 做某些其它的事情,模拟需要执行3 秒钟
            for (int i = 1; i <= 3; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(i));
                Console.WriteLine("{0}: Client executed {1} second(s).", Thread.CurrentThread.Name, i);
            }
            Console.ReadLine();

            Console.ReadKey();
        }