Example #1
0
        //4. Программа обмена двух переменных:
        //а. с использованием третьей переменной;
        //б. без использования третьей переменной.
        private static void Task4()
        {
            int a = 17;
            int b = 15;

            Console.WriteLine("a = " + a + ", b = " + b);
            int i = a;

            a = b;
            b = i;
            Console.WriteLine(@"Меняем значения переменных местами используя третью переменную. 
        В итоге a =  " + a + ", b = " + b + ".");//Попробовала перенос с @. Табуляция сохраняется. Пришлось выравнивать самой.
            MyPrint.Pause();
            a += b;
            b  = a - b;
            a -= b;
            Console.WriteLine("Меняем значения переменных местами используя сложение.\n" +
                              "\tВ итоге a =  " + a + ", b = " + b + ".");//Перенос \n и \t. Мне больше понравилось.
            MyPrint.Pause();
            a *= b;
            b  = a / b;
            a /= b;
            Console.WriteLine("Меняем значения переменных местами используя умножение.\n" +
                              "\tВ итоге a =  " + a + ", b = " + b + ".");
            MyPrint.Pause();
            Console.WriteLine("Меняем значения переменных местами используя силу мысли.\n" +
                              "\tВ итоге a =  " + b + ", b = " + a + "."); //Ну и на последок третий вариант.
                                                                           //Это магия. После ее применение пользователь будет верить, что а и б изменились :)
        }
Example #2
0
        public void Run()
        {
            string TxTFile    = @"D:\c#\TestProject\TestProject\Resources\Demo.json";
            string NewTxtFile = @"D:\c#\TestProject\TestProject\Resources\Create.txt";
            string OriginFile = @"D:\c#\TestProject\TestProject\Resources\Origin\Origin.json";
            string TargetFile = @"D:\c#\TestProject\TestProject\Resources\Target\Target.json";
            string Movefile   = @"D:\c#\TestProject\TestProject\Resources\Target\Target.txt";


            try
            {
                if (flag)
                {
                    // File.Open()

                    MyPrint.Print("--------------File.Create--------------");
                    FileStream NewTxt = CreateFile(NewTxtFile);
                    NewTxt.Close();

                    MyPrint.Print("--------------File.Delete--------------");
                    if (IsExistFile(NewTxtFile))
                    {
                        DeleteFile(NewTxtFile);
                    }

                    MyPrint.Print("--------------File.Copy--------------");
                    CopyFile(OriginFile, TargetFile);

                    MyPrint.Print("--------------File.Exists--------------");
                    if (IsExistFile(TargetFile))
                    {
                        MyPrint.Print("There are file {0}.", TargetFile);
                    }

                    MyPrint.Print("--------------File.Move--------------");
                    if (IsExistFile(Movefile))
                    {
                        DeleteFile(Movefile);
                    }
                    MoveFile(TargetFile, Movefile);

                    //  设置文件属性方法:File.SetAttributes

                    MyPrint.Print("--------------FileStream(TxTReaderWrite)--------------");
                    TxTReaderWrite(TxTFile);

                    MyPrint.Print("--------------FileStream(TxTReaderWrite02)--------------");
                    TxTReaderWrite02(TxTFile);

                    MyPrint.PrintReadKey();
                }
            }
            catch (Exception e)
            {
                MyPrint.Print(e.Message);
            }
        }
Example #3
0
 static void Main(string[] args)
 {
     //MyPrint point to function morning and evening
     MyPrint mp = new MyPrint(Morning);
     mp += Evening;
     mp -= Morning;
     //calling multicasting
     mp("Nam");
     //execute the body of all functions that are pointed by mp
 }
Example #4
0
 static void Main()
 {
     Task1and2();
     MyPrint.Pause();
     Task3();
     MyPrint.Pause();
     Task4();
     MyPrint.Pause();
     Task5();
     MyPrint.Pause();
 }
Example #5
0
        //5.а.Написать программу, которая выводит на экран мое имя, фамилию и город проживание.
        //б. Сделать вывод в центре экрана.
        //в. Сделать задание с использованием собственных методов.


        private static void Task5()
        {
            Console.Clear();//Если не почистить экран текст наползает друг на друга.
            string fullname = "Юлия Сударенко";
            string homecity = "город Москва";
            int    x        = Console.WindowWidth / 2;
            int    y        = Console.WindowHeight / 2;

            MyPrint.PrintXY(fullname, x - fullname.Length / 2, y);
            MyPrint.PrintXY(homecity, x - homecity.Length / 2, y + 1);
        }
Example #6
0
 //visit all items of a, action on each item depends on delegate
 public void VisitAll(MyPrint mp)
 {
     for (int i = 0; i < cnt; i++)
         mp(a[i]);
 }
Example #7
0
        static void Main(string[] args)
        {
            #region 委托实例化
            //C#1.0(参数完全相同)
            MyPrint          myPrint  = new MyPrint();
            InputStrDelegate delInStr = new InputStrDelegate(myPrint.PrintStr); //非静态方法实例化
            delInStr = new InputStrDelegate(MyPrint.StaticPrintStr);            //静态方法实例化

            //C# 2.0
            //匿名方法实例化
            delInStr = delegate(string strPara)
            {
                return;
            };
            delInStr = MyPrint.StaticPrintStr;//方法组转换实例化

            //省略参数列表的匿名方法(可以转换为具有任何参数列表的委托类型)
            delInStr = delegate
            {
                Console.WriteLine("委托实例化:省略参数列表的匿名方法(string)");
            };
            InputObjDelegate delInObj = delegate
            {
                Console.WriteLine("委托实例化:省略参数列表的匿名方法(object)");
            };

            //C#3.0
            //lambda表达式实例化
            delInStr = (p) =>
            {
                Console.WriteLine("委托实例化:lambda表达式");
            };
            #endregion

            #region 委托调用
            InputStrDelegate delInStrInvoke = (p) =>
            {
                Console.WriteLine("委托调用");
            };

            #region  步调用
            delInStrInvoke.Invoke("参数");
            delInStrInvoke("参数");//语法糖
            #endregion

            #region 异步调用
            //AsyncCallback参数传入回调方法(委托)
            //object参数传入回调State参数,回调方法中使用IAsyncResult参数类型的AsyncState属性获取
            //后台线程
            IAsyncResult asyncResult = delInStrInvoke.BeginInvoke("参数",
                                                                  (p) =>
            {
                Console.WriteLine(p.AsyncState);
            },
                                                                  "回调State参数");

            while (!asyncResult.IsCompleted)
            {
            }
            ;                                      //IsCompleted判断操作是否完成
            asyncResult.AsyncWaitHandle.WaitOne(); //阻塞等待操作完成
            delInStrInvoke.EndInvoke(asyncResult); //阻塞等待操作完成,获取返回类型
            #endregion
            #endregion

            #region 委托多播
            //有返回类型的委托只会返回最后一个返回类型
            //委托列表遍历执行时如遇到异常,后面的委托不会继续执行
            InputStrDelegate delInStr1 = (p) =>
            {
                Console.WriteLine("委托多播:1" + " 参数:" + p);
            };
            InputStrDelegate delInStr2 = (p) =>
            {
                Console.WriteLine("委托多播:2" + " 参数:" + p);
            };
            InputStrDelegate delInStr3 = (p) =>
            {
                Console.WriteLine("委托多播:3" + " 参数:" + p);
            };

            InputStrDelegate delInStrMC = Delegate.Combine(delInStr1, delInStr2) as InputStrDelegate;
            delInStrMC = Delegate.Combine(delInStrMC, delInStr3) as InputStrDelegate;
            delInStrMC = Delegate.Remove(delInStrMC, delInStr2) as InputStrDelegate;

            InputStrDelegate delInStrMC1 = delInStr1 + delInStr2;
            delInStrMC1 = delInStrMC1 + delInStr3;
            delInStrMC1 = delInStrMC1 - delInStr2;

            InputStrDelegate delInStrMC2 = delInStr1;
            delInStrMC2 += delInStr2;
            delInStrMC2 += delInStr3;
            delInStrMC2 -= delInStr2;
            #endregion

            #region 委托强类型
            //无返回类型委托
            Action action = () =>
            {
                Console.WriteLine("委托强类型:Action");
            };
            Action <string> actionInStr = (p) =>
            {
                Console.WriteLine("委托强类型:Action" + " 参数:" + p);
            };

            //有返回类型委托
            Func <int> func = () =>
            {
                Console.WriteLine("委托强类型:Func");
                return(0);
            };
            Func <string, int> funcInStr = (p) =>
            {
                Console.WriteLine("委托强类型:Func" + " 参数:" + p);
                return(0);
            };

            //其他委托
            Predicate <int> predicate = (p) =>
            {
                Console.WriteLine("委托强类型:Predicate" + " 参数:" + p);
                return(p > 0);
            };
            Comparison <int> comparison = (x, y) =>
            {
                Console.WriteLine("委托强类型:Comparison" + " 参数x:" + x + " 参数y:" + y);
                return(x - y);
            };
            Converter <int, string> converter = (p) =>
            {
                Console.WriteLine("委托强类型:Converter" + " 参数:" + p);
                return(p.ToString());
            };
            #endregion

            #region 委托可变性
            //返回类型协变
            OutputObjDelegate delOutObjOut = MyPrint.StaticReturnStr;

            //参数类型逆变
            InputStrDelegate delInStrIn = MyPrint.StaticPrintObj;
            #endregion

            Console.ReadKey();
        }
Example #8
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 #9
0
 public void PrintMsg(string str, MyPrint myDelegate)
 {
 }