既有公共逻辑,又有私有逻辑时 如下就可改成委托
方案一:
static void Main(string[] args)
{
sayHi("王麻子", Country.Japanesn);
Console.ReadLine();
}
public static void sayHi(string name,Country country)
{
Console.WriteLine("准备说点啥!");
switch (country)
{
case Country.Chinese:
Console.WriteLine($"{name},你好");
break;
case Country.American:
Console.WriteLine($"{name},Hi");
break;
case Country.Japanesn:
Console.WriteLine($"{name},***********8");
break;
default:
throw new Exception("error Country Type");
}
}
public enum Country
{
Chinese = 1,
American =2,
Japanesn=3
}
委托版本: 说起来委托也是需要一个第三方函数去调用它
public delegate void Hi(string name);
static void Main(string[] args)
{
var hi = new Hi(AmericanSayHi);
SayHi("小明", hi);
Console.ReadLine();
}
public static void ChineseSayHi(string name)
{
Console.WriteLine($"{name},你好");
}
public static void AmericanSayHi(string name)
{
Console.WriteLine($"{name},Hi");
}
public static void ManasicSayHi(string name)
{
Console.WriteLine($"{name},***********8");
}
public static void SayHi(string name, Hi hiDele)
{
Console.WriteLine("准备说点啥!");//公共逻辑
hiDele.Invoke(name);
}
这里提一下 Action 是一个内置委托 我们这里 可以 省略自己写委托的步骤,只要是没返回值的委托都可以使用Action
实例:
var action1 = new Action<long>();
var action2 = new Action<string, int>();
var action3 = new Action<Action<string>>();
如下:
static void Main(string[] args)
{
var hi = new Action<string>(AmericanSayHi);
SayHi("小明", hi);
Console.ReadLine();
}
public static void ChineseSayHi(string name)
{
Console.WriteLine($"{name},你好");
}
public static void AmericanSayHi(string name)
{
Console.WriteLine($"{name},Hi");
}
public static void ManasicSayHi(string name)
{
Console.WriteLine($"{name},***********8");
}
public static void SayHi(string name, Action<string> hiDele)
{
Console.WriteLine("准备说点啥!");
hiDele.Invoke(name);
}
Func也是内置的有返回值 泛型委托 ,所以一般都不需要再自己写委托,用他们两个就够了