博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第八章 委托、lambda表达式和事件
阅读量:5911 次
发布时间:2019-06-19

本文共 12590 字,大约阅读时间需要 41 分钟。

GetAStringDemo

using System;namespace Wrox.ProCSharp.Delegates{  class Program  {    private delegate string GetAString();    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());    }  }}
View Code
namespace Wrox.ProCSharp.Delegates{    struct Currency    {        public uint Dollars;        public ushort Cents;        public Currency(uint dollars, ushort cents)        {            this.Dollars = dollars;            this.Cents = cents;        }        public override string ToString()        {            return string.Format("${0}.{1,-2:00}", Dollars, Cents);        }        public static string GetCurrencyUnit()        {            return "Dollar";        }        public static explicit operator Currency(float value)        {            checked            {                uint dollars = (uint)value;                ushort cents = (ushort)((value - dollars) * 100);                return new Currency(dollars, cents);            }        }        public static implicit operator float(Currency value)        {            return value.Dollars + (value.Cents / 100.0f);        }        public static implicit operator Currency(uint value)        {            return new Currency(value, 0);        }        public static implicit operator uint(Currency value)        {            return value.Dollars;        }    }}
View Code

SimpleDelegates

namespace Wrox.ProCSharp.Delegates{  class MathOperations  {    public static double MultiplyByTwo(double value)    {      return value * 2;    }    public static double Square(double value)    {      return value * value;    }  }}
View Code
using System;namespace Wrox.ProCSharp.Delegates{  delegate double DoubleOp(double x);  class Program  {    static void Main()    {      DoubleOp[] 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();      }    }    static void ProcessAndDisplayNumber(DoubleOp action, double value)    {      double result = action(value);      Console.WriteLine(         "Value is {0}, result of operation is {1}", value, result);    }  }}
View Code

BubbleSorter

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.Delegates{  class Program  {    static void Main()    {      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);      }    }  }}
View Code
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.Delegates{  class Employee  {    public Employee(string name, decimal salary)    {      this.Name = name;      this.Salary = salary;    }    public string Name { get; private set; }    public decimal Salary { get; private set; }    public override string ToString()    {      return string.Format("{0}, {1:C}", Name, Salary);    }    public static bool CompareSalary(Employee e1, Employee e2)    {      return e1.Salary < e2.Salary;    }  }}
View Code
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.Delegates{  class BubbleSorter  {    static public void Sort
(IList
sortArray, Func
comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Count - 1; i++) { if (comparison(sortArray[i + 1], sortArray[i])) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); } }}
View Code

MulticastDelegates

using System;namespace Wrox.ProCSharp.Delegates{  class Program  {    static void Main()    {      Action
operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine(); } static void ProcessAndDisplayNumber(Action
action, double value) { Console.WriteLine(); Console.WriteLine("ProcessAndDisplayNumber called with value = {0}", value); action(value); } }}
View Code
using System;namespace Wrox.ProCSharp.Delegates{  class MathOperations  {    public static void MultiplyByTwo(double value)    {      double result = value * 2;      Console.WriteLine("Multiplying by 2: {0} gives {1}", value, result);    }    public static void Square(double value)    {      double result = value * value;      Console.WriteLine("Squaring: {0} gives {1}", value, result);    }  }}
View Code

MulticastDelegateWithIteration

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.Delegates{  class Program  {    static void One()    {      Console.WriteLine("One");      throw new Exception("Error in one");    }    static void Two()    {      Console.WriteLine("Two");    }    static void Main()    {      //Action d1 = One;      //d1 += Two;      //try      //{      //    d1();      //}      //catch (Exception)      //{      //    Console.WriteLine("Exception caught");      //}      Action d1 = One;      d1 += Two;      Delegate[] delegates = d1.GetInvocationList();      foreach (Action d in delegates)      {        try        {          d();        }        catch (Exception)        {          Console.WriteLine("Exception caught");        }      }    }  }}
View Code

AnonymousMethods

using System;namespace Wrox.ProCSharp.Delegates{  class Program  {    static void Main()    {      string mid = ", middle part,";      Func
anonDel = delegate(string param) { param += mid; param += " and this was added to the string."; return param; }; Console.WriteLine(anonDel("Start of string")); } }}
View Code

 LambdaExpressions

using System;namespace Wrox.ProCSharp.Delegates{  class Program  {    static void Main()    {      // SimpleDemos();      int someVal = 5;      Func
f = x => x + someVal; someVal = 7; Console.WriteLine(f(3)); } static void SimpleDemos() { Func
oneParam = s => String.Format("change uppercase {0}", s.ToUpper()); Console.WriteLine(oneParam("test")); Func
twoParams = (x, y) => x * y; Console.WriteLine(twoParams(3, 2)); Func
twoParamsWithTypes = (double x, double y) => x * y; Console.WriteLine(twoParamsWithTypes(4, 2)); Func
operations = x => x * 2; operations += x => x * x; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine(); } static void ProcessAndDisplayNumber(Func
action, double value) { double result = action(value); Console.WriteLine( "Value is {0}, result of operation is {1}", value, result); } }}
View Code

EventsSample

using System;namespace Wrox.ProCSharp.Delegates{  public class CarInfoEventArgs : EventArgs  {    public CarInfoEventArgs(string car)    {      this.Car = car;    }    public string Car { get; private set; }  }  public class CarDealer  {    public event EventHandler
NewCarInfo; public void NewCar(string car) { Console.WriteLine("CarDealer, new car {0}", car); RaiseNewCarInfo(car); } protected virtual void RaiseNewCarInfo(string car) { EventHandler
newCarInfo = NewCarInfo; if (newCarInfo != null) { newCarInfo(this, new CarInfoEventArgs(car)); } } }}
View Code
using System;namespace Wrox.ProCSharp.Delegates{    public class Consumer    {        private string name;        public Consumer(string name)        {            this.name = name;        }        public void NewCarIsHere(object sender, CarInfoEventArgs e)        {            Console.WriteLine("{0}: car {1} is new", name, e.Car);        }    }}
View Code
namespace Wrox.ProCSharp.Delegates{    class Program    {        static void Main()        {            var dealer = new CarDealer();            var michael = new Consumer("Michael");            dealer.NewCarInfo += michael.NewCarIsHere;            dealer.NewCar("Ferrari");            var nick = new Consumer("Sebastian");            dealer.NewCarInfo += nick.NewCarIsHere;            dealer.NewCar("Mercedes");            dealer.NewCarInfo -= michael.NewCarIsHere;            dealer.NewCar("Red Bull Racing");        }    }}
View Code

WeakEventsSample

using System.Windows;namespace Wrox.ProCSharp.Delegates{  public class WeakCarInfoEventManager : WeakEventManager  {    public static void AddListener(object source, IWeakEventListener listener)    {      CurrentManager.ProtectedAddListener(source, listener);    }    public static void RemoveListener(object source, IWeakEventListener listener)    {      CurrentManager.ProtectedRemoveListener(source, listener);    }    public static WeakCarInfoEventManager CurrentManager    {      get      {        WeakCarInfoEventManager manager = GetCurrentManager(typeof(WeakCarInfoEventManager)) as WeakCarInfoEventManager;        if (manager == null)        {          manager = new WeakCarInfoEventManager();          SetCurrentManager(typeof(WeakCarInfoEventManager), manager);        }        return manager;      }    }    protected override void StartListening(object source)    {      (source as CarDealer).NewCarInfo += CarDealer_NewCarInfo;    }    void CarDealer_NewCarInfo(object sender, CarInfoEventArgs e)    {      DeliverEvent(sender, e);    }    protected override void StopListening(object source)    {      (source as CarDealer).NewCarInfo -= CarDealer_NewCarInfo;    }  }}
View Code
namespace Wrox.ProCSharp.Delegates{  class Program  {    static void Main()    {      var dealer = new CarDealer();      var michael = new Consumer("Michael");      WeakCarInfoEventManager.AddListener(dealer, michael);      dealer.NewCar("Mercedes");      var sebastian = new Consumer("Sebastian");      WeakCarInfoEventManager.AddListener(dealer, sebastian);      dealer.NewCar("Ferrari");      WeakCarInfoEventManager.RemoveListener(dealer, michael);      dealer.NewCar("Red Bull Racing");    }  }}
View Code
using System;using System.Windows;namespace Wrox.ProCSharp.Delegates{  public class Consumer : IWeakEventListener  {    private string name;    public Consumer(string name)    {      this.name = name;    }    public void NewCarIsHere(object sender, CarInfoEventArgs e)    {      Console.WriteLine("{0}: car {1} is new", name, e.Car);    }    bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)    {      NewCarIsHere(sender, e as CarInfoEventArgs);      return true;    }  }}
View Code
using System;namespace Wrox.ProCSharp.Delegates{  public class CarInfoEventArgs : EventArgs  {    public CarInfoEventArgs(string car)    {      this.Car = car;    }    public string Car { get; private set; }  }  public class CarDealer  {    public event EventHandler
NewCarInfo; public CarDealer() { } public void NewCar(string car) { Console.WriteLine("CarDealer, new car {0}", car); if (NewCarInfo != null) { NewCarInfo(this, new CarInfoEventArgs(car)); } } }}
View Code

 

转载于:https://www.cnblogs.com/liuslayer/p/7017095.html

你可能感兴趣的文章
156
查看>>
ES2017 中的 Async 和 Await
查看>>
电子商务B2C网站购物车设计
查看>>
kaggle之数据分析从业者用户画像分析
查看>>
AWS Gets Redis, Several RDS Improvements
查看>>
c# 可空类型
查看>>
iOS开发应用学习笔记
查看>>
【SICP练习】92 练习2.65
查看>>
Day04——Python模块
查看>>
windows无法启动MySQL服务 错误1067
查看>>
JS基础学习
查看>>
mysql启动不起来了!
查看>>
apache绑定多个域名
查看>>
bzoj3295: [Cqoi2011]动态逆序对
查看>>
【转载】怎样理解阻塞非阻塞与同步异步的区别?
查看>>
String不得不说的那些事
查看>>
[转载]泛化、实现、依赖和关联的区别
查看>>
# 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
查看>>
面试题3:数组中重复的数字,不能修改原数组
查看>>
webUI自动化测试框架---”pyswat“介绍
查看>>