首页 > 代码库 > c# 委托详解
c# 委托详解
1.委托声明
2.委托入门实例
namespace ConsoleApplication1 { public delegate void methodDelegate(string str); class Program { static void Main(string[] args) { Student student = new Student(); Teacher teacher = new Teacher("王老师"); methodDelegate methodDelegate1 = new methodDelegate(student.getStudentName); methodDelegate1 += teacher.getTeacherName; //可以指向不同类中的方法! //methodDelegate1 += teacher.getClassName; 指向签名不符的方法时提示错误! methodDelegate1.Invoke("张三"); Console.ReadLine(); } } class Student { private String name = ""; public Student (String _name) { this.name = _name ; } public Student() {} public void getStudentName(String _name) { if (this.name != "" ) Console.WriteLine("Student‘s name is {0}", this.name); else Console.WriteLine("Student‘s name is {0}", _name); } } class Teacher { private String name; public Teacher(String _name) { this.name = _name; } public void getTeacherName(String _name) { if (this.name != "") Console.WriteLine("Teacher‘s name is {0}", this.name); else Console.WriteLine("Teacher‘s name is {0}", _name); } public string getClassName() { return "Eanlish"; } } }
上面代码中实现对委托的调用
最后将被调用的委托输出
3.委托的实现方式
第一种:常规实现
?
1 2 3 4 5 6 7 8 | private delegate String getAString( string parament); static void Main(String []args) { int temp = 40; getAString stringMethod = new getAString(temp.ToString); //传递temp.ToString调用委托<br> Console.WriteLine( "String is {0}" , stringMethod()); //stringMethod()调用已经接受参数的委托 Console.ReadLine(); } |
第二种:多播委托
?
1 2 3 | getAString stringMethod = new getAString(temp.ToString); stringMethod += temp.ToString; stringMethod -= temp.ToString; |
这种调用之后,按照接受参数的次数, 委托会生成一个列表,每用+=调用一次,会增加一个列表项,-=调用一次,会移除一个列表项。
第三种:委托数组
当我们定义委托 让委托形成一个数组的时候,我们可以通过遍历数组的方式来调用它
delegate double Operations(double x); class Program { static void Main() { Operations[] operations = { MathOperations.MultiplyByTwo, MathOperations.Square }; for (int i = 0; i < operations.Length; i++) { Console.WriteLine("Using operations[{0}]:", i); DisplayNumber(operations[i], 2.0); DisplayNumber(operations[i], 7.94); Console.ReadLine(); } } static void DisplayNumber(Operations action, double value) { double result = action(value); Console.WriteLine( "Input Value is {0}, result of operation is {1}", value, result); } } struct MathOperations { public static double MultiplyByTwo(double value) { return value * 2; } public static double Square(double value) { return value * value; } }
上面实例中
将委托定义好
之后就可以遍历它
委托的实现方式还有三种 持续更新中!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。