1

可能的重复:
有人可以提炼出适当的英语代表是什么吗?

我一直在尝试找出使用代表的好处,但是我仍然没有在互联网上找到任何可以正确解释它的东西。

为什么下面的代码(使用委托)比下面的代码更好?

delegate int DiscountDelegate();

class Program
{
  static void Main(string[] args)
  {
    Calculator calc = new Calculator();
    DiscountDelegate discount = null;
    if (DateTime.Now.Hour < 12)
    {
      discount = new DiscountDelegate(calc.Morning);
    }
    else if (DateTime.Now.Hour < 20)
    {
      discount = new DiscountDelegate(calc.Afternoon);
    }
    else
    {
      discount = new DiscountDelegate(calc.Night);
    }
    new ShoppingCart().Process(discount);
  }
}

class Calculator
{
  public int Morning()
  {
    return 5;
  }
  public int Afternoon()
  {
    return 10;
  }
  public int Night()
  {
    return 15;
  }
}

class ShoppingCart
{
  public void Process(DiscountDelegate discount)
  {
    int magicDiscount = discount();
    // ...
  }
}

相比:

class Program
{
  static void Main(string[] args)
  {
    Calculator calc = new Calculator();
    int discount;
    if (DateTime.Now.Hour < 12)
    {
      discount = calc.Morning();
    }
    else if (DateTime.Now.Hour < 20)
    {
      discount = calc.Afternoon();
    }
    else
    {
      discount = calc.Night();
    }
    new ShoppingCart().Process(discount);
  }
}

class Calculator
{
  public int Morning()
  {
    return 5;
  }
  public int Afternoon()
  {
    return 10;
  }
  public int Night()
  {
    return 15;
  }
}

class ShoppingCart
{
  public void Process(int discount)
  {
    int magicDiscount = discount;
    // ...
  }
}
4

0 回答 0