委托和接口另类理解,对于新手来说可能更容易理解一些,就是参数相同 可以用委托,方法相同可以用接口
委托:
private static void English(string name) {Console.WriteLine("Morning, " + name);
private static void Chinese(string name) {Console.WriteLine("早上好, " + name);
此时使用委托public delegate void Earth(string name)
private static void GetEarth(string name, Earth Saying) {Saying(name);}
GetEarth("A",English);
GetEarth("B",Chinese);
委托只是把方法当作一个值传入方法
接口:
现在有
class A(){Say(){}}
class B(){Say(){}}
类不同方法名相同此时使用接口
Interface IAandB{Say();}
class A():IAandB{Say(){}}
class B():IAandB{Say(){}}
class C()
{
Sayer(IAandB ab)
{ab.say();}
}
C c=new C();
IAandB aandb;
aandb=new A();
c.Sayer(aandb);
以下此方法和接口相同
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 商场收费
{
abstract class CashCount
{
abstract public double AcceptCash(double money);
}
class CashNormal:CashCount
{
public override double AcceptCash(double money)
{
return money;
}
}
class CashRebate:CashCount
{
double dleRebate;
public CashRebate(string strRebate)
{
this.dleRebate = Convert.ToDouble(strRebate);
}
public override double AcceptCash(double money)
{
return money * dleRebate;
}
}
class CashReturn:CashCount
{
double dleTarget, dleReturn;
public CashReturn(string strTarget, string strReturn)
{
this.dleTarget = Convert.ToDouble(strTarget);
this.dleReturn = Convert.ToDouble(strReturn);
}
public override double AcceptCash(double money)
{
return money - (dleTarget / dleReturn) * dleReturn;
}
}
class CashFactory
{
CashCount thisCC;
public CashFactory(string type)
{
CashCount cc = null;
switch(type)
{
case "全价":
cc = new CashNormal() ;
break;
case "八折":
CashRebate cr = new CashRebate("0.8");
cc = cr;
break;
case "买三百返一百":
CashReturn crl = new CashReturn("300", "100");
cc = crl;
break;
}
this.thisCC = cc;
}
public double GetResult(double money)
{
return thisCC.AcceptCash(money);
}
}
}