c#委托把方法当成参数(实例讲解)
静态方法代理:
public delegate void dogreeting(string name);
class program
{
[stathread]
static void main(string[] args)
{
//方法名当成参数传给委托类型调用
markgreeting("张三", greetingenglish);
markgreeting("李四", greetingchinese);
}
/// <summary>
/// 委托(代理的方法)
/// </summary>
/// <param name="name"></param>
/// <param name="markgreeting"></param>
private static void markgreeting(string name, dogreeting markgreeting)
{
markgreeting(name);
}
/// <summary>
/// 用英文打招呼
/// </summary>
/// <param name="name"></param>
private static void greetingenglish(string name)
{
console.writeline(name+"hello!");
}
/// <summary>
/// 用中文打招呼
/// </summary>
/// <param name="name"></param>
private static void greetingchinese(string name)
{
console.writeline(name+"你好!");
}
}
实例方法代理:
public delegate void dogreeting(string name);
public class greeting
{
/// <summary>
/// 委托(代理的方法)
/// </summary>
/// <param name="name"></param>
/// <param name="markgreeting"></param>
public void markgreeting(string name, dogreeting markgreeting)
{
markgreeting(name);
}
/// <summary>
/// 用英文打招呼
/// </summary>
/// <param name="name"></param>
public void greetingenglish(string name)
{
console.writeline(name + "hello!");
}
/// <summary>
/// 用中文打招呼
/// </summary>
/// <param name="name"></param>
public void greetingchinese(string name)
{
console.writeline(name + "你好!");
}
}
class program
{
[stathread]
static void main(string[] args)
{
greeting greetingobj = new greeting();
greetingobj.markgreeting("张三", greetingobj.greetingenglish);
greetingobj.markgreeting("李四", greetingobj.greetingchinese);
}
上一篇: C#中静态构造函数的几点说明介绍
下一篇: php的DB种使用静态方法有什么好处
推荐阅读