码迷,mamicode.com
首页 > 其他好文 > 详细

委托~~~~~~~~~~~~~

时间:2017-10-08 19:36:16      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:直接   代码   and   new   等价   线程   猪八戒   read   日本   

namespace 委托学习
{
class Program
{
static void Main(string[] args)
{
//MyDelegate.Show();

//不使用委托 耦合的东西太多,
GreetingClass.Greeting("猪八戒", 委托学习.GreetingClass.PeopleType.Chinese);

//使用委托 1.实例化委托 解耦 职责单一
委托学习.GreetingClass.GreetingHandle handle = new GreetingClass.GreetingHandle(GreetingClass.GreetingChinese);
handle.Invoke("666");//方法的调用
GreetingClass.Greeting("猪猪猪",handle);
Console.ReadLine();


//本质完全不同
//程序通过添加代码就可以实现功能,而不是修改代码===》》对扩展是开发的 对修改封闭的
//如果添加一个日本人,直接添加一个GretingJapanese的方法就好了
}
}
}

=======================================================================================

namespace 委托学习
{
//1.声明 2.实例化 3.调用
//委托可以处于Class之外
public delegate void OutNoResultNoPara();//无返回值
public delegate void OutNoResultWithPara(int x, int y);//
public class MyDelegate
{
public delegate void NoResultNoPara();
public delegate void NoResultWithPara(int x, int y);//

public delegate string NoPara();
public delegate DateTime WithPara(string name, int size);

public static void Show()
{
Student stu = new Student();
stu.Id = 123;
stu.Name = "eleven";
stu.Study();

//委托其实和类一样,也可以进行实例化
NoResultWithPara method = new NoResultWithPara(Puls);//委托的实例化===是一个void 俩个参数的参数传入
NoResultWithPara method1 = Puls;//简写的方式
method.Invoke(1, 3);//委托的调用==method(2,6); 二者完全等价
method.BeginInvoke(3, 8, null, null);//异步调用,就是另外开启一个线程去调用
//没有委托是没有异步的

 

}

public static void Puls(int x,int y)
{
Console.WriteLine("这里是Plusx={0},y={1}",x,y);
}


}
}

========================================================================================

namespace 委托学习
{
public class GreetingClass
{

public static void GreetingChinese(string name)
{
Console.WriteLine("早上好,{0}", name);
}

public static void GreetingEnglish(string name)
{
Console.WriteLine("Good Morning{0}", name);
}

public static void Greeting(string name, PeopleType type)
{
if (type == PeopleType.American)
{
Console.WriteLine("Good Morning{0}",name);
}
else if (type == PeopleType.Chinese)
{
Console.WriteLine("早上好,{0}", name);
}
else
{
throw new Exception("人物类型错误");
}

}

public static void Greeting(string name,GreetingHandle handler)
{

handler.Invoke(name);
}
//在这个委托里,传入了一个string类型的name参数,在实例化他的时候,能够点出来所有的带有string类型的name参数的方法
public delegate void GreetingHandle(string name);
public enum PeopleType
{
American,
Chinese
}
}
}

委托~~~~~~~~~~~~~

标签:直接   代码   and   new   等价   线程   猪八戒   read   日本   

原文地址:http://www.cnblogs.com/ZkbFighting/p/7638150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!