第八章 委托、lambda表达式和事件

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<T>(IList<T> sortArray, Func<T, T, bool> 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<double> operations = MathOperations.MultiplyByTwo;
      operations += MathOperations.Square;

      ProcessAndDisplayNumber(operations, 2.0);
      ProcessAndDisplayNumber(operations, 7.94);
      ProcessAndDisplayNumber(operations, 1.414);
      Console.WriteLine();
    }

    static void ProcessAndDisplayNumber(Action<double> 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<string, string> 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<int, int> f = x => x + someVal;

      someVal = 7;

      Console.WriteLine(f(3));
    }


    static void SimpleDemos()
    {
      Func<string, string> oneParam = s => String.Format("change uppercase {0}", s.ToUpper());
      Console.WriteLine(oneParam("test"));

      Func<double, double, double> twoParams = (x, y) => x * y;
      Console.WriteLine(twoParams(3, 2));

      Func<double, double, double> twoParamsWithTypes = (double x, double y) => x * y;
      Console.WriteLine(twoParamsWithTypes(4, 2));

      Func<double, double> 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<double, double> 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<CarInfoEventArgs> NewCarInfo;

    public void NewCar(string car)
    {
      Console.WriteLine("CarDealer, new car {0}", car);

      RaiseNewCarInfo(car);
    }

    protected virtual void RaiseNewCarInfo(string car)
    {
      EventHandler<CarInfoEventArgs> 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<CarInfoEventArgs> 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值