Beispiel #1
0
 static string SaySomething2()
 {
     Thread.Sleep(5);
     _Result = "Привет, мир! Случай № 2";
     Console.WriteLine("Еще привет привет", ConsoleColor.DarkGreen, "main thread");
     return("Проверка № 3");
 }
Beispiel #2
0
        static async Task <string> SaySomething1()
        {
            await Task.Delay(5);

            _Result = "Привет, мир! Случай № 1";
            Console.WriteLine("Другой привет", ConsoleColor.Yellow, "second thread");
            return("Проверка № 2");
        }
Beispiel #3
0
 public static void Info()
 {
     Console.Write
     (
         " Задача: " +
         "Определить конечный вывод в разных ситуациях "
     );
 }
 public static void Info()
 {
     Console.Write
     (
         " Задача: " +
         "Разбор нескольких ситуаций для битовых операторов и перечислений"
     );
 }
        static void Main(string[] args)
        {
            TextReader      istream = MakeInput(TestData1.Item1);
            CWriterMediator ostream = MakeOutput(TestData1.Item2);

            TextReader std_in  = Console.In;
            TextWriter std_out = Console.Out;

            Console.SetIn(istream);
            Console.SetOut(ostream);


            //   IO-цепочки для ввода-вывода.
            CIO io = new CIO();

            if (io.In(io.Number(out int n_vals), io.InEOL()))
            {
                while (n_vals > 0)
                {
                    if (io.Number(out int cmd_code).Success)
                    {
                        switch (cmd_code)
                        {
                        case 1:
                        {
                            if (io.In(io.OneOf(" "), io.Number(out int x_val)))
                            {
                                ConsoleEx.MsgBox($"c = {cmd_code}, val = {x_val}");
                            }
                            else
                            {
                                goto InvalidInput;
                            }
                        }
                        break;

                        case 2:
                        {
                            ConsoleEx.MsgBox($"c = {cmd_code}");
                        }
                        break;

                        case 3:
                        {
                            ConsoleEx.MsgBox($"c = {cmd_code}");
                        }
                        break;

                        default: goto InvalidInput;
                        }

                        if (!io.InEOL().Success)
                        {
                            goto InvalidInput;
                        }
                    }
Beispiel #6
0
        public static void Execute()
        {
            //  В данном примере я намеренно вызываю асинхронную функцию
            //  без ключевого слова await. Поэтому предупреждение нужно выключить,
            //  чтобы оно не смешивалось с настоящими ошибками и предупреждениями
            //  всего проекта, и не отвлекало тем самым от реальных проблем.
            _Result = string.Empty;
            #pragma warning disable CS4014
            SaySomething1();
            #pragma warning restore CS4014
            Console.WriteLine("Проверка № 1", ConsoleColor.DarkGreen, "main thread");
            Console.WriteLine(_Result, ConsoleColor.DarkGreen, "main thread");

            Console.WriteLine(SaySomething1().Result, ConsoleColor.DarkGreen, "main thread");
            Console.WriteLine(_Result, ConsoleColor.DarkGreen, "main thread");

            _Result = string.Empty;
            Console.WriteLine(SaySomething2(), ConsoleColor.DarkGreen, "main thread");
            Console.WriteLine(_Result, ConsoleColor.DarkGreen, "main thread");
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            int?AutoExercise = null;

            if (args.Length > 0)
            {
                if (int.TryParse(args[0], out int number))
                {
                    AutoExercise = number;
                }
            }


            var AllExercises = new List <Exercise>
            {
                new Exercise
                {
                    Name     = CLoopULongExample.Name,
                    InfoFunc = CLoopULongExample.Info,
                    ExecFunc = CLoopULongExample.Execute
                },
                new Exercise
                {
                    Name     = CBitwiseOperators.Name,
                    InfoFunc = CBitwiseOperators.Info,
                    ExecFunc = CBitwiseOperators.Execute
                },
                new Exercise
                {
                    Name     = CLoopNumbers.Name,
                    InfoFunc = CLoopNumbers.Info,
                    ExecFunc = CLoopNumbers.Execute
                },
                new Exercise
                {
                    Name     = CSharpDataTypes.Name,
                    InfoFunc = CSharpDataTypes.Info,
                    ExecFunc = CSharpDataTypes.Execute
                },
                new Exercise
                {
                    Name     = CAsyncExample1.Name,
                    InfoFunc = CAsyncExample1.Info,
                    ExecFunc = CAsyncExample1.Execute
                },
            };


Start:
            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.HorizontalTitle("Выбор примера", 5, "=", "<", ">");
            Console.ResetColor();

            Console.WriteLine("Номера примеров для запуска: ");

            int n = 1;

            foreach (Exercise exe in AllExercises)
            {
                Console.Write(n);
                Console.Write(". ");
                Console.Write(exe.Name);
                Console.WriteLine();

                n++;
            }

            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.Horizontal("=");
            Console.ResetColor();

            int choice;

            if (AutoExercise == null)
            {
                Console.CursorTop -= 2;
                string input_number = Console.ReadLine();
                Console.CursorTop += 1;


                if (!int.TryParse(input_number, out choice))
                {
                    Console.TextColor = ConsoleColor.Red;
                    Console.WriteLine("Число введено неправильно");
                    Console.ResetColor();
                    goto Start;
                }
            }
            else
            {
                choice = AutoExercise.Value;
            }


            if ((choice < 1) || (choice > AllExercises.Count))
            {
                Console.TextColor = ConsoleColor.Red;
                Console.WriteLine("Указанное число вышло за пределы допустимого");
                Console.ResetColor();
                goto Start;
            }

            choice--;


            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.HorizontalTitle(AllExercises[choice].Name, 5);
            Console.ResetColor();

            AllExercises[choice].ExecFunc();

            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.Horizontal();
            Console.ResetColor();

            goto Start;
        }
        public static void Execute()
        {
            //   Известный трюк: обмен значений двух переменных без третьего контейнера
            //   (xor swap)
            int a = 1234;
            int b = 9876;

            a = a ^ b;
            b = a ^ b;
            a = a ^ b;
            Console.WriteLine($"a = {a}, b = {b}");


            //   ulong.ToBinary -- это мой метод.
            //   В C# у класса Convert отсутствует конверсия в строку с числовой базой.
            //   Я специально сделал метод с использованием битового оператора сдвига ">>"
            //   для примера, а не использовал системный BitConverter класс.
            ulong big_number;

            big_number = 5_764_607_523_034_234_890;
            Console.WriteLine($"0b{big_number.ToBinary(32)}");

            big_number = 1;
            Console.WriteLine($"0b{big_number.ToBinary(4)}");



            //   Проверка перечисляемого типа на наличие битов
            //   в XOR режиме (должен быть только один бит)
            BoundsSpecified test_flags;


            //   У класса System.Enum мне не хватает полезных битовых методов,
            //   которые бы упростили читаемость кода и написание условий.
            //   Далее я рассматриваю два своих метода-расширения, и имеющийся:
            //     1. Энумерация имеет один включенный бит из перечисленных
            //        в маске.
            //     2. Энумерация имеет включенным все биты из заданных
            //        в маске. Этот метод есть в стандартном System.Enum описании.
            //     3. Энумерация не имеет ни одного бита из перечисленных в маске.
            //   Кроме повышения читаемости кода, основной интерес в данном примере
            //   во внутренней функции расчета количества бит в любом числе.
            //     См. CBitwiseOps.BitsCount

            //   XOR (x или width)
            test_flags = BoundsSpecified.X | BoundsSpecified.Height | BoundsSpecified.Y;
            if (test_flags.HasOneOf(BoundsSpecified.X | BoundsSpecified.Width))
            {
                Console.WriteLine
                (
                    $"В {nameof(test_flags)} есть флаг " +
                    $"'{nameof(BoundsSpecified.X)}' или " +
                    $"'{nameof(BoundsSpecified.Width)}'" +
                    $", но не оба."
                );
            }
            else
            {
                Console.WriteLine($"Ошибка в расчетах. Сюда программа никогда не должна попасть.");
            }

            if (test_flags.HasOneOf(BoundsSpecified.X | BoundsSpecified.Height))
            {
                Console.WriteLine($"Ошибка в расчетах. Сюда программа никогда не должна попасть.");
            }
            else
            {
                Console.WriteLine
                (
                    $"В {nameof(test_flags)} есть флаг " +
                    $"'{nameof(BoundsSpecified.X)}' и " +
                    $"'{nameof(BoundsSpecified.Height)}'" +
                    $", и это хорошо."
                );
            }


            //   AND (x и width)
            test_flags = BoundsSpecified.X | BoundsSpecified.Height | BoundsSpecified.Y;
            if (test_flags.HasFlag(BoundsSpecified.X | BoundsSpecified.Height))
            {
                Console.WriteLine
                (
                    $"В {nameof(test_flags)} есть оба флага: " +
                    $"'{nameof(BoundsSpecified.X)}' и " +
                    $"'{nameof(BoundsSpecified.Height)}'."
                );
            }
            else
            {
                Console.WriteLine($"Ошибка в расчетах. Сюда программа никогда не должна попасть.");
            }

            test_flags = BoundsSpecified.X | BoundsSpecified.Height | BoundsSpecified.Y;
            if (test_flags.HasFlag(BoundsSpecified.X | BoundsSpecified.Width))
            {
                Console.WriteLine($"Ошибка в расчетах. Сюда программа никогда не должна попасть.");
            }
            else
            {
                Console.WriteLine
                (
                    $"В {nameof(test_flags)} есть оба флага: " +
                    $"'{nameof(BoundsSpecified.X)}' и " +
                    $"'{nameof(BoundsSpecified.Width)}'."
                );
            }


            //   NONE (ни x, ни width)
            test_flags = BoundsSpecified.X | BoundsSpecified.Height;
            if (test_flags.HasNoneOf(BoundsSpecified.Width | BoundsSpecified.Y))
            {
                Console.WriteLine
                (
                    $"В {nameof(test_flags)} нет ни флага {nameof(BoundsSpecified.Y)}, " +
                    $"ни флага '{nameof(BoundsSpecified.Width)}'."
                );
            }
            else
            {
                Console.WriteLine($"Ошибка в расчетах. Сюда программа никогда не должна попасть.");
            }

            test_flags = BoundsSpecified.X | BoundsSpecified.Height | BoundsSpecified.Y;
            if (test_flags.HasNoneOf(BoundsSpecified.X | BoundsSpecified.Width))
            {
                Console.WriteLine($"Ошибка в расчетах. Сюда программа никогда не должна попасть.");
            }
            else
            {
                Console.WriteLine
                (
                    $"В {nameof(test_flags)} есть флаг {nameof(BoundsSpecified.X)} или " +
                    $"флаг '{nameof(BoundsSpecified.Width)}' " +
                    $"и это хорошо."
                );
            }
        }