Beispiel #1
0
        static void Main(string[] args)
        {
            //싱글라인.
            myDelegate1 add   = (a, b) => a + b;
            myDelegate2 lamda = () => Console.WriteLine("람다식");

            Console.WriteLine("11 + 22 = {0}", add(11, 22));

            lamda();

            //다중라인.(delegate가 매개변수를 대입 받는 형식으로만, 값리턴 형식으로 X)
            myDelegate Compare = (a, b) =>
            {
                if (a > b)
                {
                    Console.Write("{0}보다 {1}가 크다", b, a);
                }
                else if (a < b)
                {
                    Console.Write("{0}보다 {1}가 크다", a, b);
                }
                else
                {
                    Console.Write("{0}, {1}는 같다", a, b);
                }
            };

            Compare(11, 22);

            Console.ReadLine();
            Console.ReadKey();
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            //Lambda表达式是对匿名方法的又一次简化
            myDelegate md = name => Console.WriteLine(name);

            md("shaocx");

            //多参数的Lambda表达式
            myDelegate2 md2 = (name, age) =>
            {
                Console.WriteLine("姓名:{0},年龄:{1}", name, age);
            };

            md2("牛顿", 55);

            Console.ReadKey();
        }
Beispiel #3
0
 private void upStatus(int a, string txt)
 {
     if (InvokeRequired)
     {
         myDelegate2 md = new myDelegate2(upStatus);
         this.Invoke(md, a, txt);
     }
     else
     {
         if (a == 1)
         {
             toolStripStatusLabel2.Text = txt;
         }
         else
         {
             toolStripStatusLabel4.Text = txt;
         }
     }
 }
Beispiel #4
0
        static void Main(string[] args)
        {
            /* Creo una variable de mi clase delegado. */
            myDelegate varDelegate;

            varDelegate = new myDelegate(metodoUno);


            /*  Ejecucion del metodo */
            varDelegate("mi nombre es nacho");
            varDelegate("mi apellido es aurtenechea");
            varDelegate("mi dni es 35208599");

            /*  ahora varDelegate tiene 2 funciones. */
            varDelegate += metodoDos;
            varDelegate("se ejecuta dos veces?");
            Console.WriteLine("LIST");
            Delegate[] l = varDelegate.GetInvocationList();
            /* no se como invocar a sus metodos. */
            Console.WriteLine("");

            /*  para llamar a un metodo de instancia, necesito una instancia. */
            Program p = new Program("444");

            myDelegate2 varDelegate2;

            varDelegate2 = new myDelegate2(p.getId);

            /*  imprimo 4 veces lo que retorna la funcion almacenda en delegate2 */
            Console.WriteLine(varDelegate2());
            Console.WriteLine(varDelegate2());
            Console.WriteLine(varDelegate2());
            Console.WriteLine(varDelegate2());



            Console.ReadKey();
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            myDelegate Summa = new myDelegate(Sum);

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

            myDelegate myD = new myDelegate(Sum);

            ParamsEvent += myD;

            Console.WriteLine(ParamsEvent(array));


            myDelegate2 myD2 = new myDelegate2(Message);
            myDelegate2 myD3 = new myDelegate2(Message);

            MyEvent += myD2;
            MyEvent += myD3;

            MyEvent();

            Console.ReadKey();
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            Console.WriteLine("===============调用派生类方法==============");
            Dog dog = new Dog();                 //实例化对象 *调用派生类方法*

            dog._name = "Dog";
            dog.Age   = 12;
            dog.printfName();
            dog.Speaking();
            dog.running();
            Console.WriteLine();

            Console.WriteLine("===============采用多态的方法==============");
            Pet dogs = new Dog();            //实例化对象 *采用多态的方法*

            dogs._name = "Dogs";
            dogs.Age   = 12;
            dogs.printfName();             //这时候对象装换为Pet对象后,这里new写的就不起作用了(接下一行)
            dogs.Speaking();               //输出的就会使基类的hello,而不是您好,这就是多态
            dogs.running();
            Console.WriteLine();

            Console.WriteLine("===============利用数组批量读入==============");
            Pet[] Pets = new Pet[] { new Dog1("优化了的TOM"), new Cat1("优化了的CAT") };//这里利用数组更加简便,在原函数中有该构造函数的存在
            //注意这里数组的声明格式 int[] 名字 =new int[],比如这里是pet类创建数组,创建的数组叫做Pets,
            //等号后面 Pet[]{ 这里面是声明的个数组类型}
            for (int i = 0; i < Pets.Length; i++)             //利用数字遍历每一个方法
            {
                Pets[i].Speaking();
                Pets[i].printfName();
            }
            Console.WriteLine();

            Console.WriteLine("===============派生类用基类构造函数的实例==============");
            Dog2 dog2 = new Dog2("eminem");            //Dgg2类型是一个用了基类Pet1基类中构造函数的实例

            dog2.printfName();
            dog2.Speaking();
            Console.WriteLine();

            Console.WriteLine("===============抽象函数派生类实现后实例化==============");
            Dog3 dog3 = new Dog3();                   //抽象函数派生类实现后实例化

            dog3.Speaking();
            Console.WriteLine();

            TaiDi dog4 = new TaiDi("豆豆");

            dog4.printfName();
            dog2.Speaking();

            JinMao dog5 = new JinMao("金毛");

            dog5.printfName();
            dog5.catchThing();
            //dog5.climbtree();               这样会出错因为显式后,就不能用类实例实现方法了,应该用接口实例,如下
            Iclimb cb = (Iclimb)dog5;      //因为接口也是引用类型,但不能直接实例,通过强制转化显式实现的类的实例,来实例一个对象

            cb.climbtree();                //通过对象来调用被写了的接口方法

            Pet3 dog6 = new Pet3("ren");

            dog6.printfName();
            Pet3 dog7 = new Pet3("tian");

            dog7.printfName();
            dog7.e();                   //由于上面用了静态类加静态方法通过this Pet3的方式加入了e()这一个方法,所以这里可以直接用

            Console.WriteLine("===============显示隐式转换+重载操作符==============");
            /*Dog2类型定义在102行,Cat2类型在其下面*/
            Dog2 dog8 = new Dog2("互相转换的小动物");    //先定义一个名字叫“互相转换的小动物”的Dog2类型的动物

            dog8.Speaking();
            Cat2 cat2 = dog8;                //将dog8【隐式转换】,转换成(cat2类型)赋值给cat2

            cat2.Speaking();
            Dog2 dog9 = (Dog2)cat2;        //在这里将cat2【显式转换】,强制转换成(dog2类型)赋值给dog9

            dog9.Speaking();
            dog9++;                       //这里使用了一下重载操作符,将opera中的d1从1加到了3
            dog9.num();
            Console.WriteLine();

            var dogCage = new Cage <Dog2>(1);           //这里创建了一个cage泛型的实例化

            dogCage.Putin(new Dog2("笼子动物1"));           //将dog2类型的实例传入到dogcage中
            dogCage.Putin(new Dog2("笼子动物2"));
            var dog10 = dogCage.Takeout();              //这里将该方法返回值赋值给了dog10

            dog10.printfName();                         //因为dog10得到了泛型中的返回值,所以其类型也是Dog2的,同样也拥有Dog2类中的方法

            dog10.happy <int>(2323);                    //这里用了一个泛型方法
            dog10.happy <huamn>(new huamn());           //同样可以这样传进来一个类

            dogCage.Ishappy <Dog2>(new Dog2("泛型的小动物")); //这里是运用了泛型约束方法的实例化,所以需要满足约束,即必须是Dog2类型的参数传入

            Idog dog11 = new Idog("泛型接口狗狗");

            dog11.printfName();
            dog11.Act(new SitCmd());
            Console.WriteLine("===============下面是相关集合==============");
            Console.WriteLine();
            Console.WriteLine("===============【1】list<T>类==============");
            List <Dog1> lists = new List <Dog1>();       //声明一个list的泛型类

            lists.Add(new Dog1("list1"));                //这里用了Add()方法
            lists.Add(new Dog1("list2"));
            for (int i = 0; i < lists.Count; i++)        //这里用了count属性
            {
                lists[i].printfName();
            }
            lists.Remove(lists[1]);
            Console.WriteLine("-------------下面是Remove掉一个后的--------------");
            for (int i = 0; i < lists.Count; i++)
            {
                lists[i].printfName();
            }
            Console.WriteLine();
            Console.WriteLine("===============【2】Stack<T>类==============");
            Stack <Dog1> stacks = new Stack <Dog1>();

            stacks.Push(new Dog1("stack1"));
            stacks.Push(new Dog1("stack2"));
            Console.WriteLine("-------------peak查看栈顶但是不弹出--------------");
            var dog12 = stacks.Peek();

            dog12.printfName();
            Console.WriteLine("-------------下面将栈顶的弹出--------------");
            var dog13 = stacks.Pop();

            dog13.printfName();
            Console.WriteLine("-------------peak再次查看栈顶但是不弹出--------------");
            dog12 = stacks.Peek();
            dog12.printfName();
            Console.WriteLine("===============【3】Queue<T>类==============");
            Queue <Dog1> queues = new Queue <Dog1>();

            queues.Enqueue(new Dog1("queue1"));
            queues.Enqueue(new Dog1("queue2"));
            foreach (Dog1 item in queues)          //通过foreach遍历集合中的每一项
            {
                item.printfName();
            }
            Console.WriteLine("-------------插入两个弹出从先插入的弹出--------------");
            var dog14 = queues.Dequeue();

            dog14.printfName();
            Console.WriteLine("===============【3】dictionary<T>类==============");
            Dictionary <string, Dog1> dics = new Dictionary <string, Dog1>();

            dics.Add("labuladuo", new Dog1("doc1"));
            dics.Add("guibin", new Dog1("doc2"));
            foreach (Dog1 item in dics.Values)   //从valus中遍历各项
            {
                item.printfName();
            }
            Console.WriteLine("===============下面是委托的使用==============");
            //委托声明不能放在mian里面,这里放在了mian的上面(也可以放在某一个类里面)
            Dog1       dog15 = new Dog1("委托的狗狗");
            myDelegate mdl   = dog15.Speaking;    //注意这里只是赋值方法的引用,没有括号的!

            //myDelegate也是一种类型,所以要先实例化再使用
            mdl();
            Console.WriteLine();
            Cat2 cat3 = new Cat2("委托的猫猫");

            mdl += cat3.Speaking;                                                       //这里通过+=运算符将一个实例中再加入一个方法
            mdl();                                                                      //这时候一次调用就可以调用两个方法
            mdl += () => { Console.WriteLine("Lambda表达式在这里实现"); };                      //在delegate实例的对象中加入一个Lambda表达式
            mdl();
            myDelegate2 mdl2 = (name) => { Console.WriteLine(name + "传入参数的狗狗在这里实现"); }; //mdl2是一个可以传入参数的委托类型

            mdl2("Lambda");                                                             //在上方用lambda表达式的方法对他进行了扩展


            Console.ReadKey();           //Keep the console open in debug mode.
        }
Beispiel #7
0
        private void SetResult(string request, string response)
        {
            if (InvokeRequired)
            {
                myDelegate2 d = new myDelegate2(SetResult);
                Invoke(d, new object[] { request, response });
            }
            else
            {
                string[] req = Common.ParseCommand(request);
                string[] resp = Common.ParseCommand(response);

                //Check if need password or sms password
                if (resp[0] == "*")
                {
                    string password = "";
                    if (ShowPasswordBox("Input password", out password) == DialogResult.OK)
                        Request(Common.CreateCommand(string.Format("*{0}", password), req[1], req[2]));
                }
                else if (resp[0] == "$")
                {
                    string password = "";
                    if (ShowPasswordBox("Input sms password", out password) == DialogResult.OK)
                        Request(Common.CreateCommand(string.Format("${0}", password), req[1], req[2]));
                }
                else
                {
                    string command;
                    if (resp[1] != string.Empty)
                        command = req[1][0].ToString();
                    else
                        command = "";

                    switch (command)
                    {
                        case "0":
                            lbxSubSystems.Items.Clear();
                            string[] subSystems = resp[1].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            subSystems = SortStringArray(subSystems);
                            foreach (string subSystem in subSystems)
                                if (subSystem.Trim().Length > 0)
                                    lbxSubSystems.Items.Add(subSystem.Trim());
                            if (lbxSubSystems.Items.Count > 0)
                                lbxSubSystems.SelectedIndex = 0;
                            break;

                        case "1":
                            lbxGet.Items.Clear();
                            lbxSet.Items.Clear();
                            lbxCommands.Items.Clear();
                            btnSet.Enabled = false;
                            txtSet.Enabled = false;
                            btnExecute.Enabled = false;
                            txtParameter.Enabled = false;
                            txtGet.Text = "";
                            txtSet.Text = "";
                            txtParameter.Text = "";
                            string[] values = resp[1].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            values = SortStringArray(values);
                            string val = "";
                            string[] item;
                            foreach (string value in values)
                            {
                                val = value.Trim();
                                item = val.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                                if (item.Length < 2)
                                    continue;
                                switch (item[0])
                                {
                                    case "c":
                                        lbxCommands.Items.Add(item[1].Trim());
                                        break;

                                    case "g":
                                        KeyValuePair<string, string> kvg = new KeyValuePair<string, string>(item[1].Trim(), item[1].Trim());
                                        lbxGet.Items.Add(kvg);
                                        break;

                                    case "s":
                                        KeyValuePair<string, string> kvs = new KeyValuePair<string, string>(item[1].Trim(), item[1].Trim());
                                        lbxSet.Items.Add(kvs);
                                        break;
                                }
                                if (lbxGet.Items != null && lbxGet.Items.Count > 0)
                                    lbxGet.SelectedIndex = 0;
                                if (lbxSet.Items != null && lbxSet.Items.Count > 0)
                                {
                                    btnSet.Enabled = true;
                                    txtSet.Enabled = true;
                                    lbxSet.SelectedIndex = 0;
                                }
                                if (lbxCommands.Items != null && lbxCommands.Items.Count > 0)
                                {
                                    btnExecute.Enabled = true;
                                    txtParameter.Enabled = true;
                                    lbxCommands.SelectedIndex = 0;
                                }
                            }
                            //Get values
                            string ss = request.Substring(1);
                            StringBuilder sb = new StringBuilder("2");
                            foreach (KeyValuePair<string, string> kvp in lbxGet.Items)
                                sb.Append(string.Format("{0}:{1};", ss, kvp.Key));
                            Request(sb.ToString());
                            sb = new StringBuilder("2");
                            foreach (KeyValuePair<string, string> kvp in lbxSet.Items)
                                sb.Append(string.Format("{0}:{1};", ss, kvp.Key));
                            Request(sb.ToString());
                            break;

                        case "2":
                            string[] answers = resp[1].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            lbxGet.SelectedIndexChanged -= lbxGet_SelectedIndexChanged;
                            lbxSet.SelectedIndexChanged -= lbxSet_SelectedIndexChanged;
                            foreach (string answ in answers)
                            {
                                string[] str = answ.Split(new string[] { ":", "=" }, StringSplitOptions.RemoveEmptyEntries);
                                if (str.Length >= 3)
                                {
                                    string subSystem = str[0];
                                    string property = str[1];
                                    string value = str[2].Trim();
                                    int intValue = 0;
                                    bool isInt = int.TryParse(value, out intValue) && (intValue < 0 || intValue > 9);

                                    int index = IndexOfGetList(property);
                                    if (index != -1)
                                    {
                                        string result = (isInt ? string.Format("{0} (0x{1:x})", value, intValue) : string.Format("{0}", value));
                                        KeyValuePair<string, string> newKvp = new KeyValuePair<string, string>(property, string.Format("{0}={1}", property, result));
                                        lbxGet.Items[index] = newKvp;
                                        if (answers.Length == 1)
                                            txtGet.Text = result;
                                    }
                                    else
                                    {
                                        index = IndexOfSetList(property);
                                        if (index != -1)
                                        {
                                            string result = (isInt ? string.Format("{0} (0x{1:x})", value, intValue) : string.Format("{0}", value));
                                            KeyValuePair<string, string> newKvp = new KeyValuePair<string, string>(property, string.Format("{0}={1}", property, result));
                                            lbxSet.Items[index] = newKvp;
                                            if (answers.Length == 1)
                                                txtSet.Text = value;
                                        }
                                    }
                                }
                            }
                            lbxSet.SelectedIndexChanged += lbxSet_SelectedIndexChanged;
                            lbxGet.SelectedIndexChanged += lbxGet_SelectedIndexChanged;
                            break;

                        case "3":
                            string[] str2 = req[1].Substring(1).Split(new string[] { ":", "=" }, StringSplitOptions.RemoveEmptyEntries);
                            if (str2.Length >= 3)
                            {
                                string subSystem = str2[0];
                                string property = str2[1];
                                Request(string.Format("2{0}:{1}", subSystem, property));
                            }
                            SetResponse(response);
                            break;

                        case "4":
                            SetResponse(response);
                            break;

                        default:
                            SetResponse(string.Format("Request: {0}\n\nResponse: {1}", request, response));
                            break;
                    }
                }
            }
        }