Esempio n. 1
0
        static void Main(string[] args)
        {
            int    x = 40;
            int    y = 20;
            string s = x.ToString();

            Console.WriteLine(s);

            // 实例委托
            GetAString getAString = new GetAString(x.ToString);
            // 通过委托调用一个方法,和直接调用这个方法是一样的
            string str = getAString();  // 通过委托实例调用x中的tostring方法

            Console.WriteLine(s);

            // 调用方法
            // 1. 赋值给委托
            GetAString a = x.ToString;

            Console.WriteLine(a());
            // 2. Invoke    通过Invoke方法调用a所引用的方法
            Console.WriteLine(a.Invoke());

            // 使用委托类型作为方法的参数
            PrintString method = Method1;

            PrintStr(method);
            method = Method2;
            PrintStr(method);


            Console.ReadKey();
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            int        x          = 40;
            GetAString getAString = new GetAString(x.ToString);

            Console.WriteLine(getAString());

            var balance = new Currency(34, 50);

            getAString = balance.ToString;
            Console.WriteLine(getAString());

            DoubleOp[] operations =
            {
                MathOperations.MultiplyByTwo,
                MathOperations.Square
            };

            for (int i = 0; i < operations.Length; i++)
            {
                ProcessAndDisplayNumber(operations[i], 3);
            }
            Func <string, string> actions;

            Employee[] employees =
            {
                new Employee("Bugs Bunny", 12000),
                new Employee("Bird man",    1300),
                new Employee("Bugs Bunny",   454),
                new Employee("Bugs Bunny", 12154),
                new Employee("Bugs Bunny", 365)
            };
            BubbleSorter.Sort(employees, Employee.CompareSalary);
            //当调用多播委托的时候,调用其放啊的委托。
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            Console.WriteLine("GetAStringDemo");
            int x = 40;

            //委托绑定方法
            GetAString firstStringMethod  = new GetAString(x.ToString); //不能写成x.ToString() 这个是方法的调用 需要的是传递方法本身
            GetAString secondStringMethod = x.ToString;                 //可以使用委托推断 给委托绑定方法 两种方式 C#编译器创建的代码是一样的

            //委托调用 这两种方式相同
            firstStringMethod();
            WriteLine($"firstStringMethod() 方式调用: { firstStringMethod()}");
            firstStringMethod.Invoke();
            WriteLine($"firstStringMethod.Invoke() 方式调用: {  firstStringMethod.Invoke()}");


            var balance = new Currency(34, 50);

            //委托指向实例方法
            firstStringMethod = balance.ToString;
            WriteLine($"balance.ToString is {firstStringMethod()}");

            //委托指向静态方法
            firstStringMethod = Currency.GetCurrencyUnit;
            WriteLine($"Currency.GetCurrencyUnit is {firstStringMethod()}");

            //本节只是给委托绑定方法,使用委托调用方法
            //没有设计把文档当作参数,传递给其他方法
            //也没有体现委托的方便之处
            ReadKey();
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            int x = 40;
            //委托在语法上总是接受一个参数的构造函数,这个参数就是委托引用的方法。这个方法必须匹配最初定义委托时的签名。
            GetAString firstStringMethod = new GetAString(x.ToString);
            Console.WriteLine("string is {0}", firstStringMethod());
            //下面跟上面效果一样
            Console.WriteLine("string is {0}", firstStringMethod.Invoke());

            //把方法传递给委托变量也可以
            GetAString secondString = GoodJob;
            Console.WriteLine("second string is {0}", secondString());

            //这样两个方法都会执行,这个叫多播委托
            secondString += BadJob;
            Console.WriteLine("third string is {0}", secondString());

            secondString -= BadJob;
            Console.WriteLine("fourth string is {0}", secondString());


            GetAString Money1 = Money.GetMoney;
            Console.WriteLine("get money is {0}", Money1());

            Money m = new Money();
            Money1 = m.SendMoney;
            Console.WriteLine("send money is {0}", Money1());

            Console.ReadKey();
        }
Esempio n. 5
0
 static void Main()
 {
     int s = 20;
     GetAString firstStringMethod = new GetAString(s.ToString);
     Console.WriteLine(firstStringMethod());
     Console.WriteLine(firstStringMethod.Invoke());
     sbyte o = 127;
     //checked { ++o; }
     ++o;
     Console.WriteLine(o);
     int r=9;
     Console.WriteLine(R(ref r));
     Console.WriteLine(DayOfWeek.Friday);
     Console.WriteLine(r);
     int z;
     Console.WriteLine("z+a=out "+ F(out z));
     const int n = 6;
     int c = 4;
     Program p = new Program();
     Console.WriteLine("gET tYPE: "+p.GetType(), p.MemberwiseClone());
     Console.WriteLine(p._a);
     Console.WriteLine(b);
     Console.WriteLine(c);
     Console.WriteLine(c.GetType());
     //Console.WriteLine(F());
     for(int i = 0; i < 3; i++)
     {
         int d = 5;
         Console.WriteLine(d);
     }
     //Console.ReadLine();
     return;
 }
Esempio n. 6
0
        static void Main(string[] args)
        {
            int        x = 10;
            GetAString GetIntAsString = new GetAString(x.ToString);

            Console.WriteLine("The number is {0}", GetIntAsString.Invoke());
            Console.ReadLine();
        }
Esempio n. 7
0
        /// <summary>
        /// 测试委托
        /// </summary>
        private static void test02()
        {
            int x = 40;
            //a指向了x的tostring方法
            GetAString a = x.ToString;     //注意,这里是将x.ToString方法的引用传递给委托

            Console.WriteLine(a.Invoke()); //通过invoke方法来调用a所引用的方法
            Console.WriteLine(a());
            Console.ReadKey();
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            int        x = 40;
            GetAString firstStringMethod = new GetAString(x.ToString);

            //firstStringMethod.Invoke();
            Console.WriteLine(firstStringMethod());

            Console.ReadKey();
        }
Esempio n. 9
0
        private static void BasicDelegateTest()
        {
            int        x = 40;
            GetAString firstStringMethod = x.ToString;

            Console.WriteLine("String is {0}", firstStringMethod());
            // With firstStringMethod initialized to x.ToString(),
            // the above statement is equivalent to saying
            // Console.WriteLine("String is {0}", x.ToString());
        }
Esempio n. 10
0
        /// <summary>
        /// 测试委托
        /// </summary>
        private static void test01()
        {
            int x = 40;
            //a指向了x的tostring方法
            GetAString a = new GetAString(x.ToString);//注意,这里是将x.ToString方法的引用传递给委托

            Console.WriteLine(a.Invoke());
            Console.WriteLine(a());
            Console.ReadKey();
        }
Esempio n. 11
0
        public static void Main(string[] args)
        {
            int num = 400;
            //使用委托类型创建实例
            GetAString sasa = new GetAString(num.ToString); //sasa指向了num中的tostring方法
            GetAString dada = num.ToString;                 //第二种赋值方法;
            string     kk   = dada.Invoke();                //通过委托实例去调用num中的tostring方法;

            Console.WriteLine(sasa());                      //通过委托类型是调用一个方法,跟直接调用这个方法作用是一样的
            GetAString dde = new GetAString(num.ToString);


            Action          a  = PrintString; //action是系统内置(预定义)的一个委托类型,它可以指向一个没有返回值,没有参数的方法;
            Action <int>    a1 = PrintString; //定义了一个委托类型,这个类型可以指向一个没有返回值,有一个int参数的方法
            Action <string> a2 = PrintString; //定义了一个委托类型,这个类型可以指向一个没有返回值,有一个string参数的方法,在这里系统hi自动寻找匹配的方法;
                                              //Action可以后面通过泛型去指定action指向的方法的多个参数的类型,参数的类型跟action后面声明的委托是对应着的



            Func <int>                 fu  = State; //func中的泛型类型<>指定的是方法的返回值类型
            Func <string, string>      fu2 = State;
            Func <string, int, string> fu3 = State; //func后面必须指定一个返回值类型,参数类型可以有0~16个

            //先写参数类型,最后一个是返回值类型;
            Console.WriteLine(fu());
            Console.WriteLine(fu2("aiyanhe"));
            Console.WriteLine(fu3("aitianyi", 100));

            //多播委托
            duobo ll = PrintString;

            ll += PrintString1;
            ll += PrintString2; //一个委托有多个方法,叫做多播委托;
            ll();
            ll -= PrintString;  //减去一个指定委托
            ll -= PrintString1;
            ll -= PrintString2;
            if (ll != null)
            {
                ll();//如果委托为空,执行时会报错;
            }
            ll  = PrintString;
            ll += PrintString1;
            ll += PrintString2;
            Delegate[] sss = ll.GetInvocationList();//新建一个委托数组来接受
            foreach (var item in sss)
            {
                item.DynamicInvoke();
            }



            Console.ReadKey();
        }
Esempio n. 12
0
 private void MyGetAString(string x)
 {
     if (this.listBox1.InvokeRequired)
     {
         GetAString g = new GetAString(PopulateListBox);
         this.Invoke(g, new object[] { x });
     }
     else
     {
         PopulateListBox(x);
     }
 }
Esempio n. 13
0
        public static void Main(string[] args)
        {
            int        x = 40;
            GetAString firstStringMethod = new GetAString(x.ToString);

            Console.WriteLine($"String is {firstStringMethod()}");
            var balance = new Currency(34, 50);

            firstStringMethod = balance.ToString;
            Console.WriteLine($"String is {firstStringMethod()}");
            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine($"String is {firstStringMethod()}");
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            int        x = 40;
            GetAString firststringMethod = new GetAString(x.ToString);

            Console.WriteLine("String is {0}", firststringMethod());
            Currency banlance = new Currency(34, 50);

            firststringMethod = banlance.ToString;
            Console.WriteLine("string is {0}", firststringMethod());
            firststringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine("String is {0}", firststringMethod());
        }
Esempio n. 15
0
        public void DelegatePractice()
        {
            int        x = 40;
            GetAString firstStringMethod = x.ToString;

            Console.WriteLine($"first string is {firstStringMethod()}");
            var balance = new Currency(30, 45);

            firstStringMethod = balance.ToString;
            Console.WriteLine($"second string is {firstStringMethod()}");
            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine($"third string is {firstStringMethod()}");
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            int x = 40;
            GetAString firstStringMethod = x.ToString;
            Console.WriteLine("string is {0}", firstStringMethod());

            Currenty cc = new Currenty(34, 50);
            firstStringMethod = cc.ToString;
            Console.WriteLine("string is {0}", firstStringMethod());

            firstStringMethod = new GetAString(Currenty.GetCurrencyUnit);
            Console.WriteLine("string is {0}", firstStringMethod());
            Console.ReadKey();
        }
Esempio n. 17
0
        protected override bool RunInternal()
        {
            int x = 40;
            //GetAString firstStringMethod = new GetAString(x.ToString);

            GetAString firstStringMethod = x.ToString;

            Type type = firstStringMethod.GetType();

            Console.WriteLine(firstStringMethod.GetType());

            Console.WriteLine("String is {0}", firstStringMethod());

            return(true);
        }
Esempio n. 18
0
        public static void Run()
        {
            #region 验证委托可以指定不同实例上引用的不同方法,不用考虑方法是否静态,只要方法的签名匹配委托定义即可
            int        x = 40;
            GetAString firstStringMethod = x.ToString;
            Console.WriteLine($"string is {firstStringMethod()}");

            var balance = new Currency(34, 1);
            firstStringMethod = balance.ToString;
            Console.WriteLine($"string is {firstStringMethod()}");

            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine($"string is {firstStringMethod()}");
            #endregion
        }
Esempio n. 19
0
        static void Main()
        {
            int x = 40;
              GetAString firstStringMethod = x.ToString;
              Console.WriteLine("String is {0}", firstStringMethod());

              Currency balance = new Currency(34, 50);

              // firstStringMethod references an instance method
              firstStringMethod = balance.ToString;
              Console.WriteLine("String is {0}", firstStringMethod());

              // firstStringMethod references a static method
              firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
              Console.WriteLine("String is {0}", firstStringMethod());
        }
Esempio n. 20
0
        static void Main()
        {
            int        x = 40;
            GetAString firstStringMethod = x.ToString;

            Console.WriteLine("String is {0}", firstStringMethod());

            Currency balance = new Currency(34, 50);

            // firstStringMethod references an instance method
            firstStringMethod = balance.ToString;
            Console.WriteLine("String is {0}", firstStringMethod());

            // firstStringMethod references a static method
            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine("String is {0}", firstStringMethod());
        }
Esempio n. 21
0
        public void TestDelegate()
        {
            int i = int.Parse("99");

            int        x = 40;
            GetAString firstStringMethod = new GetAString(x.ToString);
            string     s = firstStringMethod();

            firstStringMethod = x.ToString; // 委托推断:只传送地址的名称

            Currency balance = new Currency(34, 50);

            firstStringMethod = balance.ToString;
            s = firstStringMethod();

            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            s = firstStringMethod();
        }
    static void Main()
    {
      int x = 40;
      GetAString firstStringMethod = new GetAString(x.ToString);
      WriteLine($"String is {firstStringMethod()}");
      // With firstStringMethod initialized to x.ToString(),
      // the above statement is equivalent to saying
      // Console.WriteLine("String is {0}", x.ToString());

      var balance = new Currency(34, 50);

      // firstStringMethod references an instance method
      firstStringMethod = balance.ToString;
      WriteLine($"String is {firstStringMethod()}");

      // firstStringMethod references a static method
      firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
      WriteLine($"String is {firstStringMethod()}");
    }
Esempio n. 23
0
        static void Main()
        {
            int        x = 40;
            GetAString firstStringMethod = new GetAString(x.ToString);

            Console.WriteLine($"String is {firstStringMethod()}");
            // With firstStringMethod initialized to x.ToString(),
            // the above statement is equivalent to saying
            // Console.WriteLine("String is {0}", x.ToString());

            var balance = new Currency(34, 50);

            // firstStringMethod references an instance method
            firstStringMethod = balance.ToString;
            Console.WriteLine($"String is {firstStringMethod()}");

            // firstStringMethod references a static method
            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine($"String is {firstStringMethod()}");
        }
Esempio n. 24
0
        //所有返回字符串的无参方法都可以跟下面的委托变量(实例)匹配

        static void Main()
        {
            int x = 40;
            //生成委托变量实例firstStringMethod
            //次候firstStringMethod作用等价于x.x.ToString
            GetAString firstStringMethod = new GetAString(x.ToString);

            Console.WriteLine($"String is {firstStringMethod()}");
            // Console.WriteLine("String is {0}", x.ToString());

            var balance = new Currency(34, 50);

            // firstStringMethod references an instance method
            firstStringMethod = balance.ToString;
            Console.WriteLine($"String is {firstStringMethod()}");

            // firstStringMethod references a static method
            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine($"String is {firstStringMethod()}");
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            int i = 40;
            // 创建并初始化委托实例,将ToString()方法的地址赋予委托变量
            // 委托总是接受一个参数的构造函数
            GetAString firstStringMethod = new GetAString(i.ToString);

            Console.WriteLine("firstStringMethod() is {0} ", firstStringMethod());
            // 委托实例提供圆括号与调用委托类的Invoke()方法完全相同
            Console.WriteLine("firstStringMethod() is {0} ", firstStringMethod.Invoke());
            // 委托推断:编译器解析委托实例为需要的特定类型
            GetAString secondStringMethod = i.ToString;

            Currency balance = new Currency(34, 50);

            // firstStringMethod委托调用一个实例方法
            firstStringMethod = new GetAString(balance.ToString);
            Console.WriteLine("String is {0} ", firstStringMethod());
            // firstStringMethod委托调用一个静态方法
            firstStringMethod = new GetAString(Currency.GetCurrencyUint);
            Console.WriteLine("String is {0} ", firstStringMethod());

            Console.Read();
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            int i = 40;

            //使用正常方法转行类型
            string a = i.ToString();//通过ToString方法转换成字符串类型

            Console.WriteLine(a);

            //使用委托转行类型
            //GetAString b = new GetAString(i.ToString);//委托初始化注册方法的第一种方式
            GetAString b = i.ToString;////委托初始化注册方法的第二种方式,常用的方式
            string     s = b();

            PrintString method = Method1;

            PrintStr(method);
            method = Method2;
            PrintStr(method);

            Console.WriteLine(s);

            Console.ReadKey();
        }
Esempio n. 27
0
        public void SimpleDelagateLambda()
        {
            Console.WriteLine("\n\t DemoLambda.SimpleDelegateLambda()...");

            // init delegate using delegate declaration:
            // public delegate string GetAString(); // declared in class above
            GetAString fL1 = () => "Lambda implements delegate GetAString";

            Console.WriteLine($"use GetAString() via fL1 delegate: '{fL1()}' ");

            // init delegate using delegate declaration:
            // public delegate string GetAString(); // declared in class above
            GetAString fM2 = () => this.ToString();

            Console.WriteLine($"use GetAString() via fM2 delegate: '{fM2()}' ");

            // init delegate using delegate declaration:
            // public delegate string GetAString(); // declared in class above
            GetAString fL2 = () => $"Lambda #{Id} implements delegate GetAString";

            Console.WriteLine($"use GetAString() via fL2 delegate: '{fL2()}' ");

            // init delegate using delegate declaration:
            // public delegate int ScaleBy10(int n); // declared in class above
            ScaleBy10 fL3 = n => n * 10;

            Console.WriteLine($"use ScaleBy10(27) via fL3 delegate: '{fL3(27)}' ");

            // init delegate using delegate declaration:
            // public delegate int ScaleBy10(int n); // declared in class above
            ScaleBy10 fM4 = n => this.MultiplyByTen(n);

            Console.WriteLine($"use MultiplyByTen(27) via fM4 delegate: '{fM4(27)}' ");

            Console.WriteLine("\n\t DemoLambda.SimpleDelegateLambda()... done!");
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            int        x = 40;
            GetAString firstStringMethod = x.ToString;

            Console.WriteLine("String is {0}", firstStringMethod());

            Currency balance = new Currency(34, 50);

            firstStringMethod = balance.ToString;
            Console.WriteLine("String is {0}", firstStringMethod());

            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine("String is {0}", firstStringMethod());
            Single j = 5.4f;

            Console.WriteLine(j);

            char ch = Convert.ToChar('a' | 'b' | 'c');

            Console.WriteLine(ch);

            Console.ReadKey();
        }
Esempio n. 29
0
        public void SimpleDelagate()
        {
            Console.WriteLine("\n\t DemoLambda.SimpleDelagate()...");

            // init delegate using delegate declaration:
            // public delegate string GetAString(); // declared in class above
            GetAString fM1 = new GetAString(ToString); // init delegate

            Console.WriteLine($"use GetAString() via fM1 delegate: '{fM1()}' ");
            GetAString fM2 = ToString;  // init delegate without 'new'

            Console.WriteLine($"use GetAString() via fM2 delegate: '{fM2()}' ");

            // init delegate using delegate declaration:
            // public delegate int ScaleBy10(int n); // declared in class above
            ScaleBy10 fM3 = new ScaleBy10(MultiplyByTen);

            Console.WriteLine($"use MultiplyByTen(27) via fM3 delegate: '{fM3(27)}' ");
            ScaleBy10 fM4 = MultiplyByTen;  // init delegate without 'new'

            Console.WriteLine($"use MultiplyByTen(27) via fM4 delegate: '{fM4(27)}' ");

            Console.WriteLine("\n\t DemoLambda.SimpleDelagate()... done!");
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            int        x = 40;
            GetAString firstStringMethod = new GetAString(x.ToString);

            Console.WriteLine(firstStringMethod());
            Console.WriteLine(x.ToString());//等同于firstStringMethod()
            Console.WriteLine();
            GetAString FirstStringMethod = x.ToString;

            Console.WriteLine(FirstStringMethod());
            Currency balance = new Currency(34, 50);

            FirstStringMethod = balance.ToString;
            Console.WriteLine(FirstStringMethod());
            FirstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine(FirstStringMethod());
            Console.WriteLine();
            DoubleOp[] operations =
            {
                MathOperations.MultiplyByTwo,
                MathOperations.Square
            };//把委托的事例放在数组中
            Func <double, double>[] Operations =
            {
                MathOperations.MultiplyByTwo,
                MathOperations.Square
            };
            for (int i = 0; i < operations.Length; i++)
            {
                Console.WriteLine("Using operations[{0}]:", i);
                ProcessAndDisplayNumber(operations[i], 2.0);
                ProcessAndDisplayNumber(operations[i], 7.94);
                ProcessAndDisplayNumber(operations[i], 1.414);
                Console.WriteLine();
            }
            Console.WriteLine();


            Employee[] employees =
            {
                new Employee("Bugs Bunny",            20000),
                new Employee("Elmer Fudd",            10000),
                new Employee("Daffy Duck",            25000),
                new Employee("Wile Coyote",     1000000.38m),
                new Employee("Foghorn Leghorn",       23000),
                new Employee("RoadRunner", 50000)
            };
            BubbleSorter.Sort(employees, Employee.CompareSalary);
            foreach (var employee in employees)
            {
                Console.WriteLine(employee);
            }

            Console.WriteLine();
            Action <double> Moloperations = MathOperations.MultiplyBytwo;

            Moloperations += MathOperations.square;
            ProcessAndDisplayNumber3(Moloperations, 2.0);
            ProcessAndDisplayNumber3(Moloperations, 7.94);
            ProcessAndDisplayNumber3(Moloperations, 1.414);
            Console.WriteLine();


            string mid = ",好喜欢,";//lambda表达式
            Func <string, string> lambda = param =>
            {
                param += mid;
                param += "于瑶瑶.";
                return(param);
            };

            Console.WriteLine(lambda("陈灰灰"));
            Console.WriteLine();
            Func <string, string> oneParam = s =>
                                             string.Format("加进去的是:" + s.ToUpper());

            Console.WriteLine(oneParam("定义test参数"));
            Console.WriteLine();
            Func <double, double, double> twoParams = (a, b) => a * b;

            Console.WriteLine(twoParams(3, 2));
            int             someVal = 5;
            Func <int, int> f       = c => c + someVal;

            Console.WriteLine(f(5));

            /*var values = new List<int> { 10, 20, 30 };
             * var funcs = new List<Func<int>> ();
             * foreach (var val in values)
             * {
             *  funcs.Add(() => val);
             * }
             * foreach(var f in funcs)
             * {
             *  Console.WriteLine((f()));
             * }*/
            Console.WriteLine();
            var dealer  = new CarDealer();
            var michael = new Consumer("Michael");

            dealer.NewCarInfo += michael.NewCarIsHere;
            dealer.NewCar("法拉利");
            var john = new Consumer("John");

            dealer.NewCarInfo += john.NewCarIsHere;
            dealer.NewCar("宝马");
            dealer.NewCarInfo -= michael.NewCarIsHere;
            dealer.NewCar("新车");
        }
Esempio n. 31
0
        public void getDescription(GetAString methodDescription, string color)
        {
            var mycolorDescription = methodDescription(color);

            Console.WriteLine($"My color is {mycolorDescription}");
        }
Esempio n. 32
0
        static void Main(string[] args)
        {
            Console.WriteLine("Pi is " + MathTest.GetPi());
            int x = MathTest.GetSquareOf(5);

            Console.WriteLine("Square of 5 is " + x);

            MathTest math = new MathTest();

            math.value = 30;
            Console.WriteLine("Value field of math variable contains " + math.value);
            Console.WriteLine("Square of 30 is " + math.GetSquare());

            int i = 0;

            int[] ints = { 0, 1, 2, 4, 8 };

            Console.WriteLine("i = " + i);
            Console.WriteLine("ints[0] = " + ints[0]);
            Console.WriteLine("Calling SomeFunction.");

            ParameterTest.SomeFunction(ints, ref i);
            Console.WriteLine("i = " + i);
            Console.WriteLine("ints[0] = " + ints[0]);

            ParameterTest test = new ParameterTest();

            test.TestMethod(12);

            Program p = new Program();

            //p.Age=20;
            Console.WriteLine(p.Age);

            MyNumber num = new MyNumber(43);

            var doctor = new { FirstName = "James", MiddleName = "T", LastName = "Kirk" };

            Console.WriteLine(doctor.FirstName);

            SaverAccount counter = new SaverAccount();

            counter.PayIn(399);
            counter.Withdraw(100);
            Console.WriteLine(counter.ToString());

            int num1 = 4;

            Console.WriteLine(num1 & (-num1));

            fanxing fx = new fanxing();

            fx.boxing();
            fx.noBoxing();

            var list1 = new LinkedList();

            list1.AddLast(2);
            list1.AddLast(4);

            foreach (int k in list1)
            {
                Console.WriteLine(k);
            }

            var dm = new DocumentManager <Document>();

            dm.AddDocument(new Document("Title A", "Sample A"));
            dm.AddDocument(new Document("Title B", "Sample B"));

            dm.DisplayAllDocuments();

            if (dm.IsDocumentAvailable)
            {
                Document d = dm.GetDocument();
                Console.WriteLine(d.Content);
            }

            int        t = 40;
            GetAString firstStringMethod = t.ToString;

            Console.WriteLine("String is {0}", firstStringMethod());

            Currency balance = new Currency(34, 50);

            firstStringMethod = balance.ToString;
            Console.WriteLine("String is {0}", firstStringMethod());

            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine("String is {0}", firstStringMethod());

            DoubleOp[] operations =
            {
                MathOperations.MultiplyByTwo,
                MathOperations.Square
            };

            for (int q = 0; q < operations.Length; q++)
            {
                Console.WriteLine("Using operations[{0}]:", q);
                ProcessAndDisplayNumber(operations[q], 2.0);
                ProcessAndDisplayNumber(operations[q], 7.94);
                ProcessAndDisplayNumber(operations[q], 1.414);
                Console.WriteLine();
            }

            Employee[] employees =
            {
                new Employee("Bugs Bunny",            20000),
                new Employee("Elmer Fudd",            10000),
                new Employee("Daffy Duck",            25000),
                new Employee("Will Coyote",     1000000.38m),
                new Employee("Foghorn Leghorn",       23000),
                new Employee("RoadRunner", 50000)
            };

            BubbleSorter.Sort(employees, Employee.CompareSalary);

            foreach (var employee in employees)
            {
                Console.WriteLine(employee);
            }

            string mid = ",middle part,";
            Func <string, string> anonDel = delegate(string param)
            {
                param += mid;
                param += " and this was added to the string.";
                return(param);
            };

            Console.WriteLine(anonDel("Start of string"));

            Func <string, string> lambda = param =>
            {
                param += mid;
                param += " and this was added to the string.";
                return(param);
            };

            Console.WriteLine(lambda("Start of string"));

            RegExp reg = new RegExp();

            reg.reg();

            Spider spider = new Spider();

            //spider.autoExcute();
            spider.WatcherStrat(@"D:\Documents and Settings\Desktop\SourceHanSansCN", "*.html");

            //UseShell useshell = new UseShell();
            //useshell.excute();

            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            int        x = 40;
            GetAString firstStringMethod = x.ToString;

            Console.WriteLine($"String is {firstStringMethod()}");
            var balance = new Currency(34, 50);

            firstStringMethod = balance.ToString;
            Console.WriteLine($"String is {firstStringMethod()}");

            firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
            Console.WriteLine($"String is {firstStringMethod()}");
            Console.WriteLine($"------------------");
            DoubleOp[] operations =
            {
                MathOperations.MultiplayByTwo,
                MathOperations.Square
            };
            //声明参数类型是double,返回类型是double的Func委托,
            //对于Func<a,b>, b类型是返回类型,a类型是输入参数类型,输入参数类型可以有多个
            //例如Func<a,a,c,b>,表示3个参数,分别是a类型,a类型,c类型,返回值是b类型
            Func <double, double>[] funcOperations =
            {
                MathOperations.MultiplayByTwo,
                MathOperations.Square
            };
            for (int i = 0; i < operations.Length; i++)
            {
                Console.WriteLine($"Using operation[{i}]");
                ProcessAndDisplayNumber(operations[i], 2.0);
                ProcessAndDisplayNumber(operations[i], 7.94);
                ProcessAndDisplayNumber(operations[i], 1.414);
            }

            for (int i = 0; i < funcOperations.Length; i++)
            {
                Console.WriteLine($"Using operation[{i}]");
                ProcessFuncAndDisplayNumber(funcOperations[i], 2.0);
                ProcessFuncAndDisplayNumber(funcOperations[i], 7.94);
                ProcessFuncAndDisplayNumber(funcOperations[i], 1.414);
            }

            Console.WriteLine($"------------------");

            Employee[] employees =
            {
                new Employee("Tom",       20000),
                new Employee("Jack",      10000),
                new Employee("Bob",       15000),
                new Employee("Roy",  100000.38m),
                new Employee("Lily",      23000),
                new Employee("Jean",      50000),
            };
            //将Employee.CompareSalary方法作为委托参数传入BubbleSorter.Sort方法
            BubbleSorter.Sort(employees, Employee.CompareSalary);
            foreach (var item in employees)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"------------------");

            //多播委托,一个委托可以包含多个方法,但是委托签名必须返回void,否则只能得到委托调用最后一个方法的结果
            Action <double> actionOperations = MathOperations.ActionMultiplayByTwo;

            actionOperations += MathOperations.ActionSquare;
            ProcesActionAndDisplayNumber(actionOperations, 2.0);
            ProcesActionAndDisplayNumber(actionOperations, 7.94);
            ProcesActionAndDisplayNumber(actionOperations, 1.414);
            Console.WriteLine($"------------------");

            string mid = ", middle part,";
            //匿名方法
            //   Func<string, string> anonDel = delegate(string param)
            //   {
            //       param += mid;
            //       param += " and this was added to the string";
            //       return param;
            //};
            //使用lambda表达式的匿名方法,参数的类型和委托定义的类型对照
            Func <string, string> anonDel = param =>
            {
                param += mid;
                param += " and this was added to the string";
                return(param);
            };

            Console.WriteLine(anonDel("Start of string"));

            Console.WriteLine($"------------------");

            var dealer   = new CarDealer();
            var valtteri = new Consumer("Valtteri");

            dealer.NewCarInfo += valtteri.NewCarIsHere;
            dealer.NewCar("Williams");

            var max = new Consumer("Max");

            dealer.NewCarInfo += max.NewCarIsHere;
            dealer.NewCar("Mercedes");
            dealer.NewCarInfo -= valtteri.NewCarIsHere;
            dealer.NewCar("Ferrari");
        }
Esempio n. 34
0
        public static void DemoDelegates()
        {
            int        x             = 40;
            GetAString fStringMethod = new GetAString(x.ToString);
            GetAString sStringMethod = x.ToString;                      //Also can be done like this...


            Con.WriteLine($"x String is {fStringMethod()}");
            Con.WriteLine($"x String is {sStringMethod()}");

            //Simple Delagte Example
            DoubleOp[] ops =
            {
                MathOps.TimesTwo,
                MathOps.Sqr
            };


            for (int i = 0; i < ops.Length; i++)
            {
                Con.WriteLine($"Using ops[{ops[i].Method}]:");
                ProAndDis(ops[i], 2.0);
                ProAndDis(ops[i], 7.35);
                ProAndDis(ops[i], 1.555);
            }

            //Now with a Func to it.
            Func <double, double>[] fOps =
            {
                MathOps.TimesTwo,
                MathOps.Sqr
            };
            var val = 3.35;

            foreach (var o in fOps)
            {
                ProAndDispFunc(o, ref val);
                Console.WriteLine($@"Val: {val}");
            }

            //Using our bubble Sort with our Employee Records
            Employee[] emps = { new Employee(1001, (decimal)110233.35), new Employee(1002, (decimal)20233.35), new Employee(1003, (decimal)130233.35) };
            BubbleSorter.Sort(emps, Employee.CompareSalary);

            //Multicast delegates
            Action <double> operAction = MathOpsV.TimesTwo;

            operAction += MathOpsV.Sqr;

            ProcAndDisAction(operAction, 3.5);

            operAction -= MathOpsV.TimesTwo;
            operAction += MathOpsV.TimesTwo;    //Order of execution not guaranteed

            ProcAndDisAction(operAction, 3.5);

            Delegate[] delInv = operAction.GetInvocationList();
            foreach (var delegatev in delInv)
            {
                var a = (Action <double>)delegatev;
                Con.WriteLine($"{a.Method}");

                //Somehow it should be possible to invoke these methods individually.
            }

            Action a1 = One;

            a1 += Two;
            try
            {
                a1();
            }
            catch (Exception ex)
            {
                Con.WriteLine($"Exception, {ex.Message}, caught!");
            }

            Delegate[] dA = a1.GetInvocationList();
            foreach (Action d in dA)
            {
                try
                {
                    d();
                }
                catch (Exception ex)
                {
                    Con.WriteLine($"Exception, {ex.Message}, what exception!");
                }
            }

            //ToDo: Anonymous Methods P 197
            string mid = ", middle bit, ";

            Func <string, string> anonDel = delegate(string parm)
            {
                parm += mid;
                parm += " end bit.";
                return(parm);
            };

            Con.WriteLine(anonDel("Start"));
        }
Esempio n. 35
0
 static void Main(string[] args)
 {
     int x = 40;
     GetAString firstStringMethod = new GetAString(x.ToString);
     Debug.WriteLine("String is {0}", firstStringMethod());
 }