首页 > 代码库 > c# delegate
c# delegate
C# version 1.0 delegate
// Declare delegate type PerformCalculator public delegate int PerformCalculator(int x, int y); public class SampleClass { private int Add(int x, int y) { return x + y; } private int Minus(int x, int y) { return x - y; } public int DoCalculate(string type, int x, int y) { // Create PerformCalculator instance PerformCalculator add = new PerformCalculator(Add); PerformCalculator minus = new PerformCalculator(Minus); if (type == "add") // Execute delegate return add(x, y); else return minus(x, y); } }
C# version 2.0 introduced anonymous method, creating anonymous methods is essentially a way to pass a code block as a delegate paramater.
// Declare delegate type PerformCalculator public delegate int PerformCalculator(int x, int y); public class Delegate {public int DoCalculate(string type, int x, int y) { // Create PerformCalculator instance PerformCalculator add = delegate(int dx, int dy) { return dx + dy; }; PerformCalculator minus = delegate(int dx, int dy) { return dx - dy; }; if (type == "add") // Execute delegate return add(x, y); else return minus(x, y); } }
C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise.
// Declare delegate type PerformCalculator public delegate int PerformCalculator(int x, int y); public class Delegate { public int DoCalculate(string type, int x, int y) { // Create PerformCalculator instance PerformCalculator add = (dx, dy) => dx + dy; PerformCalculator minus = (dx, dy) => dx - dy; if (type == "add") // Execute delegate return add(x, y); else return minus(x, y); } }
Delegates are the basis for Events.
The delegate must be instantiated with a method or lamda expression that has a compatiable return type and input parameter.
c# delegate
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。