static void Main(string[] args) { Console.WriteLine("***** Sync Delegate Review *****\n"); // print out the ID of the executing thread Console.WriteLine($"Main() invoked on thread { Thread.CurrentThread.ManagedThreadId }."); // invoke Add() in a synchronous manner BinaryOp b = new BinaryOp(Add); // could also write b.Invoke(10, 10) int answer = b.Invoke(10, 10); // these lines will not execute until the Add() method has completed Console.WriteLine($"Doing more work in Main()!"); Console.WriteLine($"10 + 10 is { answer }."); // just for fun Console.WriteLine($"5 + 10 is { b.Invoke(5, 15) }."); Console.Write($"\n\nPress <Enter> to Exit. . ."); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("Delegate Review"); Console.WriteLine("ID выполняющегося потока {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp delegateObject = new BinaryOp(Add); //Добавили метод в делегат //вызов делегата - подразумевает вызов всех методов внтури IAsyncResult asyncObject = delegateObject.BeginInvoke(5, 10, null, null); while (!asyncObject.IsCompleted) { Console.WriteLine("Нагрузка и расчёт"); } int asyncAnswer = delegateObject.EndInvoke(asyncObject); Console.WriteLine("{0} - asyncResult", asyncAnswer); //Метод Add усыпит поток на 5 сек, поскольку он синхронный, рантайм остановится на 5 сек, и потом //продолжит выполнение int answer = delegateObject.Invoke(5, 10); Console.WriteLine("Имитация бездействия - ждун"); Console.WriteLine("{0} - result", answer); Console.ReadLine(); }
public static void Test() //或换成Main,单独测试运行 //创建一个指向SimpleMath.Add()方法的BinaryOp对象 { BinaryOp bo = new BinaryOp(SimpleMath.Add); //使用委托间接调用Add方法 //Console.WriteLine("10 + 10 is {0}.", bo(10, 10)); Console.WriteLine("10 + 10 is {0}.", bo.Invoke(10, 10)); //①编译错误!方法不匹配 //BinaryOp bo1 = new BinaryOp(SimpleMath.SquareNumber); //Console.WriteLine("9 * 9 is {0}.", bo1(9)); //②.NET委托与可以指向实例方法 BinaryOp bo2 = new BinaryOp(new SimpleMath().NSAdd); Console.WriteLine("20 + 30 is {0}.", bo2(20, 30)); //③显示委托对象的信息: DisplayDelegateInfo(bo); DisplayDelegateInfo(bo2); bo += new SimpleMath().NSAdd; DisplayDelegateInfo(bo); Console.ReadKey(); }
public void TestDelegatesGeneric() { var d = new BinaryOp <int>(BinaryAnd); //create delegate instance generic Console.WriteLine(d(2, 7)); //call delegate Console.WriteLine(d.Invoke(2, 7)); //call delegate directly }
static void main(string[] args) { Console.WriteLine("***** Simple Delegate Example*****\n"); // instantiate an instance of "simpleMathClass" see above SimpleMath m = new SimpleMath(); // so now lets add the add method of the instance of 'simpleMath' to it. // 'BinaryOp is a delegates that takes 2 ints as parameters and returns an int as a result. BinaryOp b = new BinaryOp(m.Add); //invoke Add() method directly using delegate object Console.WriteLine("Direct invocation... 10+10 is {0}", b(10, 10)); Console.ReadLine(); //invoke Add() method indirectly using delegate object Console.WriteLine("Indirect invocation,.... 10 + 10 is {0}", b.Invoke(10, 10)); Console.ReadLine(); // Change the target method on the fly b = new BinaryOp(m.Substract); Console.WriteLine("Replace add with subtract"); Console.ReadLine(); //invoke the substract method by direactly invoking that delegate Console.WriteLine("Direct invocation.... 15 - 5 is {0}", b(15, 5)); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // Create a BinaryOp delegate object that // "points to" SimpleMath.Add(). // ••• DELEGATE INSTANCE // This is NET 1.x style insantiation BinaryOp b = new BinaryOp(SimpleMath.Add); // •••• Invoke Add() method indirectly using delegate object. Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); // Shorthand Console.WriteLine("10 + 10 is {0}", b(10, 10)); Console.ReadLine(); // NET 2.0 instantiation BinaryOp c = SimpleMath.Subtract; Console.WriteLine("20 - 10 is {0}", c(20, 10)); Console.WriteLine(); // Second example string[] s1 = { "Hello", "World" }; Console.WriteLine("{0} {1}", s1); StringUtils.Case(s1, StringUtils.Lower); Console.WriteLine("{0} {1}", s1); StringUtils.Case(s1, StringUtils.Upper); Console.WriteLine("{0} {1}", s1); }
public void AddOperation() { var d = new BinaryOp(SimpleMath.Add); //static method //var d2 = new BinaryOp(SimpleMath.SquareNumber); // <-- compile-time error! it is type safe! DisplayDelegateInfo(d); Console.WriteLine("10 + 10 is {0}", d(10, 10)); Console.WriteLine("10 + 10 is {0}", d.Invoke(10, 10)); // it is equivalent }
static void SimpleDelegateExample() { System.Console.WriteLine("=> Simple Delegate Example:"); BinaryOp b = new BinaryOp(SimpleMath.Add); // hmmm, it is same pattern with C++ callback System.Console.WriteLine("10 + 10 is {0}", b(10, 10)); System.Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); // <-- Invoke() is not necessary called explicitly; Console.ReadLine(); }
static void Main(string[] args) { BinaryOp b = new BinaryOp(SimpleMath.Add); Console.WriteLine("10 + 10 is {0}", b(10,10)); Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); //Also ok Console.WriteLine(); DisplayDelegateInfo(b); SimpleMath m = new SimpleMath(); BinaryOp bInst = new BinaryOp(m.Subtract); DisplayDelegateInfo(bInst); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // .NET delegates can also point to instance methods as well. SimpleMath m = new SimpleMath(); BinaryOp b = new BinaryOp(m.Add); // Error! Method does not match delegate pattern! // BinaryOp b2 = new BinaryOp(SimpleMath.SquareNumber); // Invoke Add() method using delegate. Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); DisplayDelegateInfo(b); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("*****Simple Delegate Example * ****\n"); // Создать объект делегата BinaryOp, который "указывает" на SimpleMath.Add() //BinaryOp b = new BinaryOp(SimpleMath.Add); // Делегаты .NET могут также указывать на методы экземпляра. SimpleMath simpleMath = new SimpleMath(); BinaryOp b = new BinaryOp(simpleMath.Add); // Вывести сведения об объекте DisplayDelegateInfo(b); // Вызвать метод Add() косвенно с использованием объекта делегата. Console.WriteLine("10 + 10 is {0}", b(10, 10)); Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // 创建一个指向SimpleMath.Add()方法的BinaryOp对象 SimpleMath m = new SimpleMath(); BinaryOp b = new BinaryOp(m.Add); DisplayDelegateInfo(b); // 使用委托对象间接调用Add()方法 // Invoke()在这里被调用了 Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); // 编译器错误!方法不匹配委托的模式 //BinaryOp b2 = new BinaryOp(SimpleMath.SquareNumber); Console.ReadLine(); }
static void Main(string[] args) { BinaryOp operationDelegate = new BinaryOp(Delegates.Add); //sau operationDelegate = Program.Add; Console.WriteLine(operationDelegate(3, 5)); Console.WriteLine(operationDelegate.Invoke(3, 5)); DisplayDelegateInfo(operationDelegate); MessageClass message = new MessageClass(); PrintMessage messageDelegate = message.PrintMessage; messageDelegate("Hello world!"); messageDelegate = message.PrintReverseMessage; messageDelegate("Hello world!"); DisplayDelegateInfo(messageDelegate); Console.ReadKey(); }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // Create a BinaryOp delegate object that // "points to" SimpleMath.Add(). BinaryOp b = new BinaryOp(SimpleMath.Add); // Invoke Add() method indirectly using delegate object. //Console.WriteLine("10 + 10 is {0}", b(10, 10)); b.Invoke(12, 12); //Console.WriteLine("10 + 10 is {0}", b(10, 10)); // Compiler error! Method does not match delegate pattern! //BinaryOp b2 = new BinaryOp(SimpleMath.SquareNumber); DisplayDelegateInfo(b); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); // Ошибка! Метод не может быть вызван через данный деоегат! // BinaryOp b2 = new BinaryOp(SimpleMath.SquareNumber); // Делегаты .NET могут также указывать на методы экземпляров. SimpleMath m = new SimpleMath(); BinaryOp b = new BinaryOp(m.Add); DisplayDelegateInfo(b); // Вызовем метод Add() косвенным образом, используя делегат. Console.WriteLine("10 + 10 is {0}", b.Invoke(10, 10)); BinaryOp b2 = new BinaryOp(m.Subtract); Console.WriteLine("10 - 10 is {0}", b2.Invoke(10, 10)); Console.ReadLine(); }
static void Main(string[] args) { // 可以通过反射来查看Binary这个类型的相关信息,也可以通过ildasm.exe反编译来查看 BinaryOp b = new BinaryOp(SimpleMath.Add); Console.WriteLine("10 + 11 = {0}", b(10, 11)); Console.WriteLine("10 + 11 = {0}", b.Invoke(10, 11)); DisplayDelegateInfo(b); Car c1 = new Car("SlugBug", 100, 10); c1.Exploded += OnCarEngineEvent; c1.AboutToBlow += OnCarEngineEvent2; c1.AboutToBlow += OnCarEngineEvent3; for (int i = 0; i < 6; i++) { c1.Accelerate(20); } Console.ReadLine(); }
static void Main(string[] args) { #region Delegates Console.WriteLine("Delegates"); BinaryOp add = new BinaryOp(OOP.Delegates.BasicMath.Add); int result1 = add(42, 17); int resuly2 = add.Invoke(42, 17); //BinaryOp error = new BinaryOp( BasicMath.Square()); OOP.Delegates.BasicMath math = new OOP.Delegates.BasicMath(); BinaryOp mul = new BinaryOp(math.Mul); DisplayDelegateInfo(add); DisplayDelegateInfo(mul); OOP.Delegates.Cars cars = new Cars(50); cars.RegisterEventHndler(new OOP.Delegates.Cars.CarEvent(Program.OnCarEvent)); cars.RegisterEventHndler(Program.AnptherCarEventHandler); //for (int i = 0; i < 5; i++) //{ // cars.Accelerate(10); // Console.WriteLine($"Car speed: {cars.Speed}"); //} //cars.DeregisterCarEventHandler(Program.OnCarEvent); //for (int i = 0; i < 5; i++) //{ // cars.Accelerate(-10); // Console.WriteLine($"Car speed: {cars.Speed}"); //} //OOP.Delegates.GenericDelegate<string> strDelegate= new GenericDelegate<string>(Program.StringMethod); //OOP.Delegates.GenericDelegate<int> intDelegate = new GenericDelegate<int>(Program.StringMethod); //strDelegate("Hello World"); //intDelegate(42); //Action<int, int> mathSub = new Action<int, int>(BasicMath.Sub); //Action<string> action = Program.OnCarEvent; //action("Action is invoked"); //Func<int, int, int> mathAdd = new Func<int, int, int>(BasicMath.Add); //int result3 = mathAdd(42, 17); //cars.Started += Program.OnCarEvent; //cars.Started += Program.AnptherCarEventHandler; //cars.Started("Car started"); //cars.SpeedChanged += Program.OnCarSpeedChanged; #endregion #region Enumeration Console.WriteLine("Enumeration"); OOP.Enums.BorderSide topSide = Enums.BorderSide.Top; bool isTop = (topSide == OOP.Enums.BorderSide.Top); Console.WriteLine(isTop); Console.WriteLine($"topSide is {topSide}"); Console.WriteLine($"BorderSide is {BorderSide.Top}"); Console.WriteLine($"Size of BorderSide enum is {sizeof(BorderSide)}"); #endregion #region Generics Console.WriteLine("Generics"); var stack = new OOP.Generics.Stacks <int>(); stack.Push(5); stack.Push(6); stack.Push(7); Console.WriteLine($"Stack member is {stack.Pop()}, {stack.Pop()}"); var stackString = new OOP.Generics.Stacks <string>(); stackString.Push("Armenia"); // stackString.Push(string.Empty); stackString.Push("South Korea"); Console.WriteLine($"{stackString.Pop()}, {stackString.Pop()}"); #endregion #region Inheritance Console.WriteLine("INheritance"); OOP.Inheritance.Car car = new OOP.Inheritance.Car(); car.Speed = 60; OOP.Inheritance.Bus bus = new OOP.Inheritance.Bus(); bus.Speed = 40; // TODO: Create class diagram OOP.Inheritance.Manager garegin = new OOP.Inheritance.Manager("Garegin", age: 42, salary: 1_800_000, ssn: "12345678", stopOptions: 1500); OOP.Inheritance.SalesPerson marine = new OOP.Inheritance.SalesPerson(); IEnumerator ie = new OOP.Interfaces.Countdown(); while (ie.MoveNext()) { Console.WriteLine(ie.Current); } ((OOP.Interfaces.ILogger) new OOP.Interfaces.Countdown()).Log("message"); #endregion #region Interfaces Console.WriteLine("Interface"); double totalArea = 0; foreach (OOP.Interfaces.Shape shapee in LoadShapesFromDatabaseI()) { shapee.Print(); totalArea += shapee.Area; } Console.WriteLine(); Console.WriteLine($"Total area: {totalArea}"); #endregion #region Lambdas Console.WriteLine("Lambdas"); //C# 1.0 PrintDelegate print1 = new PrintDelegate(Program.PrintMethod); //C# 2.0 PrintDelegate print2 = delegate(string msg) { Console.WriteLine(msg); }; //C# 3.0 PrintDelegate print3 = (string msg) => Console.WriteLine(msg); print1("Hello"); print2("C Sharp"); print3("Language"); Func <int, int, int> mathAdd = (int x, int y) => x + y; Func <int, int> mathAbs = (int x) => { if (x < 0) { return(-x); } else { return(x); } }; List <int> numbers = new List <int> { 42, 17, 65, 24, 31, 6, 58, 0 }; List <int> evenNumbers = numbers.FindAll(x => x % 2 == 0); foreach (int number in evenNumbers) { Console.Write($"{number}, "); } Console.WriteLine(); int denominator = int.Parse(Console.ReadLine()); int local = 0; Action action = () => Console.WriteLine($"Value: {local}"); local = 1; action(); #endregion #region Polymorphism Console.WriteLine("Polymorphism"); OOP.Polymorphism.Circle circle = new OOP.Polymorphism.Circle(1); OOP.Polymorphism.Shape shape = new OOP.Polymorphism.Circle(1); Console.WriteLine($"The area of circle with radius 1 is {circle.GetArea()}"); Console.WriteLine($"The area of shape is {shape.GetArea()}"); //Shape[] shapes = LoadShapesFromDatabase(); //double area = 0, perimeter = 0; //foreach (Shape shape in shapes) //{ // area += shape.GetArea(); // perimeter += shape.Perimeter; //} //Console.WriteLine($"Total area of all shapes: {area}"); //Console.WriteLine($"Total perimeter of all shapes: {perimeter}"); // Downcasting example //Circle downcastedCircle = (Circle)shape; //Rectangle rectangle = (Rectangle)shape; //if (rectangle != null) // Console.WriteLine($"Shape is a rectangle."); //else // Console.WriteLine("Shape is not a rectangle"); //if (shape is Circle) //{ // Circle c = (Circle)shape; // Console.WriteLine($"Diameter: {c.Diameter}"); //} //// Override ToString method. //Console.WriteLine(); //Console.WriteLine("We received the following shapes from the database:"); //foreach (Shape shape in shapes) //{ // Console.WriteLine($"A {shape} with area {shape.GetArea()} and perimeter {shape.Perimeter}"); //} #endregion }