/// <summary>
/// 委托是一个类,它定义了方法的类型,
/// 使得可以将方法当作另一个方法的参数来进行传递,
/// 这种将方法动态地赋给参数的做法,
/// 可以避免在程序中大量使用If-Else(Switch)语句,
/// 同时使得程序具有更好的可扩展性。
/// </summary>
public class Class1
{
public string str = string.Empty;
#region 1
public void GreetPeople(string s)
{
EnglishGreeting(s);
}
public void ChineseGreeting(string name)
{
Console.WriteLine("早上好, " + name);
}
public void EnglishGreeting(string s)
{
str = "hello ";
}
#endregion
#region 2
public enum Languages
{
English,Chinese
}
public void ChineseGreetings(string name)
{
str = "早上好";
}
public void EnglishGreetings(string s)
{
str = "hello ";
}
public void GreetPeoples(string s, Languages l)
{
switch (l)
{
case Languages.English:
EnglishGreetings(s);
break;
case Languages.Chinese:
ChineseGreetings(s);
break;
}
}
#endregion
#region 3
public string ChineseGreetinges(string name)
{
str = "早上好";
}
public string EnglishGreetinges(string s)
{
return str = "hello ";
}
public delegate string GreetingDelegate(string name);
public string GreetPeopless(string name, GreetingDelegate l)
{
return l(name);
}
/// 委托是一个类,它定义了方法的类型,
/// 使得可以将方法当作另一个方法的参数来进行传递,
/// 这种将方法动态地赋给参数的做法,
/// 可以避免在程序中大量使用If-Else(Switch)语句,
/// 同时使得程序具有更好的可扩展性。
/// </summary>
public class Class1
{
public string str = string.Empty;
#region 1
public void GreetPeople(string s)
{
EnglishGreeting(s);
}
public void ChineseGreeting(string name)
{
Console.WriteLine("早上好, " + name);
}
public void EnglishGreeting(string s)
{
str = "hello ";
}
#endregion
#region 2
public enum Languages
{
English,Chinese
}
public void ChineseGreetings(string name)
{
str = "早上好";
}
public void EnglishGreetings(string s)
{
str = "hello ";
}
public void GreetPeoples(string s, Languages l)
{
switch (l)
{
case Languages.English:
EnglishGreetings(s);
break;
case Languages.Chinese:
ChineseGreetings(s);
break;
}
}
#endregion
#region 3
public string ChineseGreetinges(string name)
{
str = "早上好";
}
public string EnglishGreetinges(string s)
{
return str = "hello ";
}
public delegate string GreetingDelegate(string name);
public string GreetPeopless(string name, GreetingDelegate l)
{
return l(name);
}
#endregion
后台:
Class1 c=new Class1();
MessageBox.Show(c.GreetPeopless("zrw", c.EnglishGreetinges));