public static void TestDelegate() { //Reparem na assinatura do MathDelegate. (int(int,int)) significa que retorna int, e que tem como argumentos dois inteiros. //Isto será expresso na forma de (x, y) que são os dois argumentos seguidos de => e da operação. //Caso a operação tenha mais que duas instruções, deverá ser colocada entre chavetas. Ou seja, ((x,y) => x+y) var sum = new MathDelegate((x, y) => x + y); var sumTotal = sum.Invoke(1, 2); sumTotal = sum(1, 2); //Agora com duas operações sum = new MathDelegate((x, y) => { var temp = 12; temp *= x + y; return(temp); }); sumTotal = sum.Invoke(1, 2); //No entanto não podemos mudar a variável para outro delegate, mesmo que os argumentos e o tipo de retorno seja o mesmo. //sum = new GenericDelegate<int>((x, y) => x + y); //Chamar um genérico também é simples var newSum = new GenericDelegate <int>((x, y) => x + y); sumTotal = newSum(1, 2); var newSumPrinter = new GenericDelegate <string, int>((x, y) => (x + y).ToString()); var sumPrint = newSumPrinter(1, 2); //Vamos testar? }
private void RadioMultiplication_CheckedChanged(object sender, EventArgs e) { // with function (commented above) // Calculation = Multiplication; // or with lambda Calculation = (a, b) => Decimal.Round(Decimal.Multiply(a, b), 2); }
static void Main(string[] args) { //Using Method Program p = new Program(); MathDelegate methodDel = new MathDelegate(p.Multiply); int methodResult = methodDel(23, 6); Console.WriteLine("Multiply Method Result : " + methodResult); //Using Annonymous Method MathDelegate AnnDel = delegate(int num1, int num2) { return(num1 * num2); }; int annResult = AnnDel(87, 12); Console.WriteLine("Annonymous Method Result : " + annResult); //Using Lambda Expression MathDelegate lambdaDel = (num1, num2) => num1 * num2; int lambdaResult = lambdaDel(45, 2); Console.WriteLine("Lambda Expression Result : " + lambdaResult); Console.ReadKey(); }
private void RadioSubtraction_CheckedChanged(object sender, EventArgs e) { // with function (commented above) // Calculation = Subtraction; // or with lamda Calculation = (a, b) => Decimal.Round(a - b, 2); }
static void Main(string[] args) { Console.WriteLine(File.ReadAllText("somefile.txt")); File.WriteAllText("somenewfile.txt", "more junk".ToRandomCase()); MathDelegate someOperation = Add; someOperation(2, 4); List <int> numbers = new List <int> { 1, 2, 3 }; if (numbers is IEnumerable <int> ) { } multiply(c: 5, a: 2); string input = Console.ReadLine(); if (double.TryParse(input, out double result)) { Console.WriteLine(result * 10); } WriteLine("Hello World!"); }
private void RadioDivision_CheckedChanged(object sender, EventArgs e) { // with function (commented above) // Calculation = Division; // or lamda Calculation = (a, b) => Decimal.Round(Decimal.Divide(a, b), 2); }
private static void TestDelegateExample() { MathDelegate md1, md2, md3, md4; md1 = new MathDelegate(SimpleMath.Add); md2 = new MathDelegate(SimpleMath.Subtract); md3 = new MathDelegate(SimpleMath.Multiply); md4 = new MathDelegate(SimpleMath.Divide); Random rand = new Random(); int n1 = rand.Next(1, 100), n2 = rand.Next(1, 100); int add = md1(n1, n2); int sub = md2(n1, n2); int mult = md3(n1, n2); int div = md4(n1, n2); String format = "add = {0}{1}subtract = {2}{1}multiply = {3}{1}divide = {4}"; String nl = "\r\n"; Console.WriteLine("n1 = {0} , n2 = {1}", n1, n2); String msg = String.Format(format, add, nl, sub, mult, div); Console.WriteLine(msg); }
static void Main(string[] args) { MathDelegate mathOperation = Add; int a = 5; int b = 7; int result = mathOperation(a, b); Console.WriteLine("The delegate operation result is {0}.", result); mathOperation = Subtract; result = mathOperation(a, b); Console.WriteLine("The delegate operation result is {0}.", result); mathOperation = Multiple; result = mathOperation(a, b); Console.WriteLine("The delegate operation result is {0}.", result); mathOperation = Power; result = mathOperation(a, b); Console.WriteLine("The delegate operation result is {0}.", result); Console.ReadKey(); }
static void Main(string[] args) { SalDelegate deleg = new SalDelegate(GetSalary); var salary = deleg.Invoke(30, 800); Console.WriteLine("salary = {0}", salary); deleg += GetIncentives; //referencing more than one method var incent = deleg.Invoke(30, 800); Console.WriteLine("Incentives = {0}", incent); //multicaste delegate MathDelegate mathdeleg = new MathDelegate(Add); mathdeleg += Subtract; mathdeleg += Multiply; mathdeleg += Divide; mathdeleg.Invoke(950, 95); Program objP = new Program(); objP.Print = new printhandler(objP.Onprint); //Registering on print event handler with print event objP.show(); //raise the print event(defined inside the show method) Console.ReadKey(); }
static void Mycallback(IAsyncResult ir) { MathDelegate d = ir.AsyncState as MathDelegate; long result = d.EndInvoke(ir); Console.WriteLine("result=" + result); }
public void IncrementHelper(int[] arr, MathDelegate worker) { int increment = 99; foreach (var element in arr) { worker(element, increment); } }
public int MathOperation(MathDelegate mathDelegate, params int[] list) { int m = list[0]; foreach (var item in list) { m = mathDelegate(m, item); } return(m); }
static void Main(string[] args) { MathDelegate m = new MathDelegate(Add); m += Sub; m += mul; m += div; m.Invoke(950, 11); Console.ReadKey(); }
static void Main(string[] args) { Delegate1Class d = new Delegate1Class(); // MathDelegate md = new MathDelegate(d.add); //md(100,200);//Delgate:one method get executed and it holds the reference of one method MathDelegate md = d.add; md += d.substract;//multicasting Delegate:making delegate to hold the reference of more than one method at a time here md holds both the methods md(1000, 2000); Console.ReadKey(); }
static void Main(string[] args) { MathDelegate performMathOperations = null; performMathOperations += Add; performMathOperations += Multiply; performMathOperations += Divide; performMathOperations += Substract; performMathOperations += Remainder; performMathOperations(20, 3); }
static void Main(string[] args) { // Assign type Method1Delegate to variable delegate1 and point it to Method1. Method1Delegate delegate1 = Method1; delegate1(); // Assign type Method2Delegate to variable delegate2 and point it to Method2. Method2Delegate delegate2 = Method2; Console.WriteLine("Method 2 float value " + delegate2()); // Assign type Method3Delegate to variable delegate3 and point it to Method3. Method3Delegate delegate3 = Method3; delegate3("Andreas", 25, 1.82f); // Create a new instance of Math class. Math mathObject = new Math(); // Assign type MathDelegate to variable math and point it to Addition method in Math class. MathDelegate math = mathObject.Addition; Console.WriteLine("Addition 17 + 18 = " + math(17, 18)); // Assign math variable to Multiplication method in Math class. math = mathObject.Multiplication; Console.WriteLine("Multiplication 3 * 7 = " + math(3, 7)); // Assign type MyDelegate to variable myDelegate and point it to Method4. MyDelegate myDelegate = Method4; // Assign another method to myDelegate myDelegate += Method5; // Invoke myDelegate, it will call both Method4 and Method5. myDelegate(); // Assign type IntDelegate to variable addition and point it to Lambda Expression IntDelegate addition = (num1, num2) => num1 + num2; Console.WriteLine("Addition 13 + 4 = " + addition(13, 4)); // Assign type IntDelegate to variable subtraction and point it to Lambda Expression IntDelegate subtraction = (num1, num2) => num1 - num2; Console.WriteLine("Subtraction 8 - 2 = " + subtraction(8, 2)); // Assign type IntDelegate to variable subtraction and point it to Lambda Expression FloatDelegate multiplication = (num1, num2) => num1 * num2; Console.WriteLine("Multiplication 4.2 * 3.1 = " + multiplication(4.2f, 3.1f)); // Assign type IntDelegate to variable division and point it to Lambda Expression FloatDelegate division = (num1, num2) => num1 / num2; Console.WriteLine("Multiplication 4 / 32 = " + division(4, 32)); }
private static void Main(string[] args) { //ConnectAzureRepos(); ToStringDelegate toString = PrintToString; Student Biggo = new Student("Biggo"); Dog Bingo = new Dog(45); toString(Bingo); toString(Biggo); PrintDelegate delegatedPrint = PrintInt; delegatedPrint(32); delegatedPrint = PrintMoney; //can also be called with the Invoke Method delegatedPrint.Invoke(45); PrintHelper(delegatedPrint, 7000); delegatedPrint = PrintInt; PrintHelper(delegatedPrint, 7000); //multicast delegates PrintDelegate multiPrintDelegate = PrintInt; multiPrintDelegate += PrintMoney; multiPrintDelegate += PrintHexadecimal; //call the delegate and all the methods associated with it multiPrintDelegate(500); //multiCast multiplication MathDelegate delegatedMath = Add; delegatedMath += Subtract; delegatedMath += Multiply; delegatedMath += Divide; delegatedMath(500, 2); PairDelegate(); Console.ReadLine(); }
static void Main(string[] args) { #region 匿名类与var var obj = new { age = 20, name = "小张", id = 10001 }; Console.WriteLine("姓名:{0},年龄:{1},学号:{2}", obj.name, obj.age, obj.id); var b = "adadad"; //var arry = { 1, 2, 3 }; //var arry1 = new int[] { 1, 2, 3 }; //var a = null; #endregion #region 扩展方法 Console.WriteLine("-----------扩展方法---------------"); ExtendMethodTest(); ExtendSrudentTest(); #endregion #region 委托 Console.WriteLine("-------------委托-------------"); //3将委托与方法关联:即创建委托对象关联方法 CalculatorDelegate objAdd = new CalculatorDelegate(Add); //4通过委托调用方法 int result = objAdd(3, 6); Console.WriteLine(result); //断开委托所关联的方法 objAdd -= Add; //关联减法 objAdd += Sub; Console.WriteLine(objAdd(20, 10)); #endregion #region 匿名方法与Lambal表达式 Console.WriteLine("-------匿名方法-------"); CalculatorDelegate add = delegate(int c, int d) { return(c + d); }; Console.WriteLine(add(20, 30)); Console.WriteLine("---Lambal表达式---"); CalculatorDelegate add1 = (int c, int d) => { return(c + d); }; Console.WriteLine(add1(20, 30)); CalculatorDelegate add2 = (c, d) => { return(c + d); }; Console.WriteLine(add2(5, 5)); MathDelegate math = a => a * a; Console.WriteLine(math(10)); #endregion Console.ReadLine(); }
// Declare a delegate public void NamedMethod() { DelegateSamples m = new DelegateSamples(); // Delegate instantiation using "Multiply" MathDelegate d = m.Multiply; // Invoke the delegate object. Console.WriteLine("Invoking the delegate using 'Multiply':"); for (int i = 1; i <= 5; i++) { d(i, 5); } Console.WriteLine(""); }
static void Main(string[] args) { MathDelegate mathDelegate1 = MathOps.Addition; MathDelegate mathDelegate2 = MathOps.Subtraction; MathDelegate mathDelegate3 = MathOps.Multiply; MathDelegate mathDelegate4 = MathOps.Division; //multicast delegate MathDelegate mathDelegate = mathDelegate1; mathDelegate += mathDelegate2; mathDelegate += mathDelegate3; mathDelegate += mathDelegate4; //call delegate with parameters mathDelegate(10, 20); }
static void Main(string[] args) { MathDelegate del1 = new MathDelegate(Add); MathDelegate del2 = new MathDelegate(Subtract); MathDelegate del3 = new MathDelegate(Multiply); MathDelegate del4 = new MathDelegate(Divide); //del1(100, 200); //del1 = new MathDelegate(Subtract); //del1(100, 200); MathDelegate del5 = del1 + del2 + del3 + del4; del5.Invoke(200, 300); Console.WriteLine(); del5 -= del2; del5.Invoke(200, 300); Console.ReadKey(); }
public static float UserMathOperation() { Console.WriteLine("Please enter the left-hand number of the operation"); float left = float.Parse(Console.ReadLine()); Console.WriteLine("Please enter the right-hand number of the operation"); float right = float.Parse(Console.ReadLine()); string operation = null; Console.WriteLine("Please specify which math operation you would like to execute"); do { Console.WriteLine("Enter either add, subtract, multiply, divide, or power"); operation = Console.ReadLine(); }while (operation != "add" && operation != "subtract" && operation != "multiply" && operation != "divide" && operation != "power"); MathDelegate toInvoke = ReturnMathDelgByString(operation); return(ExecuteMathFunction(left, right, toInvoke)); }
static void Main(string[] args) { //Multicast Delegate MathDelegate mathdeleg = new MathDelegate(Add); mathdeleg += Subtract; mathdeleg += Multiply; mathdeleg += Divide; mathdeleg.Invoke(950, 95); Program objP = new Program(); objP.Print += new PrintHandler(objP.OnPrint); //Registering OnPrint event handler with print event objP.Show(); // raise the print event(defined inside the show method Console.ReadKey(); }
static void Main() { //Instatiation of delgate objects MathDelegate addDel, subDel, multiDel, divideDel; //Creation of Delegates addDel = new MathDelegate(Add); subDel = new MathDelegate(Subtract); multiDel = new MathDelegate(Multiplication); divideDel = new MathDelegate(Division); Console.WriteLine("----Gathering Numbers----"); Console.WriteLine("Enter a number above 0 or enter -1 to close the application... "); Console.WriteLine("Please enter the first number: "); double firstNum = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please enter the second number: "); double secondNum = Convert.ToDouble(Console.ReadLine()); //To exit application if (firstNum == -1) { Environment.Exit(-1); } //addDel(firstNum, secondNum); //subDel(firstNum, secondNum); //multiDel(firstNum, secondNum); // divideDel(firstNum, secondNum); // Console.ReadKey(); //multicasting delegates Console.WriteLine("----This is the multicasted delegate----"); multiCastDel(addDel, firstNum, secondNum); multiCastDel(subDel, firstNum, secondNum); multiCastDel(multiDel, firstNum, secondNum); multiCastDel(divideDel, firstNum, secondNum); }
static void Main(string[] args) { Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId); MathClass mat = new MathClass(); MathDelegate del1, del2; del2 = new MathDelegate(MathClass.Multiply); //Invoke(del2); //List<string> mystrings = new List<string>(); //mystrings.Add("monday"); //mystrings.Add("tuesday"); //mystrings.Add("wednesday"); //mystrings.Add("thursday"); //mystrings.Add("friday"); //Action<string> myaction = new Action<string>(Print); //mystrings.ForEach(myaction); //MyDelegate multicast; //multicast=new MyDelegate(mat.M1); //multicast+=new MyDelegate(MathClass.M2); //multicast.Invoke(); del1 = new MathDelegate(mat.Add); //Console.WriteLine(del1.Invoke(111,99)); IAsyncResult iar = del1.BeginInvoke(11, 9, new AsyncCallback(Mycallback), del1); ThreadPool.QueueUserWorkItem(M1); ThreadPool.QueueUserWorkItem(M1); ThreadPool.QueueUserWorkItem(M1); ThreadPool.QueueUserWorkItem(M2); Console.WriteLine("Main End"); Console.ReadLine(); }
static void Main(string[] args) { MathDelegate deleg = new MathDelegate(Addnum); var num = deleg.Invoke(5, 10); Console.WriteLine("Addition={0}", num); deleg += Mulnum; var num1 = deleg.Invoke(5, 10); Console.WriteLine("Multiplication={0}", num); deleg += Subnum; var num2 = deleg.Invoke(5, 10); Console.WriteLine("Subtraction={0}", num); deleg += Divnum; var num3 = deleg.Invoke(5, 10); Console.WriteLine("Division={0}", num); }
static void Main(string[] args) { MathDelegate math = Double; double y = math(3); Console.WriteLine(y); MathDelegate math2 = delegate(double x) { return(x * x); }; double z = math2(4); Console.WriteLine(z); MathDelegate math3 = x => x * x * x; double c = math3(5); Console.WriteLine(c); Console.ReadKey(); }
static void Main(string[] args) { MathClass math = new MathClass(); MCDelegate del = new MCDelegate(math.M1); del += new MCDelegate(MathClass.M2); del += new MCDelegate(math.M1); del(); del -= new MCDelegate(math.M1); del(); MathDelegate del1, del2; del1 = new MathDelegate(math.Add); del2 = new MathDelegate(MathClass.Multiply); //MyInovoke(del1); AsyncCallback mycallback = delegate(IAsyncResult ir) { long result = del1.EndInvoke(ir); Console.WriteLine($"The add result done async is {result}"); }; IAsyncResult iar = del1.BeginInvoke(111, 333, mycallback, null); Console.WriteLine(del2.Invoke(333, 455)); Console.ReadLine(); }
static void Main(string[] args) { MulticastDemo md = new MulticastDemo(); MathDelegate dadd = new MathDelegate(MulticastDemo.Add); MathDelegate dsub = new MathDelegate(MulticastDemo.Sub); MathDelegate dmul = new MathDelegate(md.Mul); MathDelegate ddiv = new MathDelegate(md.Div); // chaining all delegate MathDelegate rootd = dadd + dsub + dmul + ddiv; rootd = rootd - dsub - dmul - ddiv; rootd(12, 12); // earlier path dsub(12, 10); dmul.Invoke(10, 10); // delegate return type DelegateReturn dr = new DelegateReturn(DelegateReturnDemo.MethodOne); dr = dr + DelegateReturnDemo.MethodTwo; int valueReturn = dr(); Console.WriteLine($"Delegate Return for method Two: {DelegateReturnDemo.MethodOne()}"); Console.WriteLine($"Delegate Return for method Two: {DelegateReturnDemo.MethodTwo()}"); // delegate out example DelegateOut delegateOut = new DelegateOut(DelegateOutDemo.MethodOne); delegateOut = delegateOut + DelegateOutDemo.MethodTwo; int returnOut = 0; delegateOut(out returnOut); Console.WriteLine($"Delegate OUT for method Two: { returnOut}"); delegateOut -= DelegateOutDemo.MethodTwo; delegateOut(out returnOut); Console.WriteLine($"Delegate OUT for method One: { returnOut}"); }
public static void multiCastDel(MathDelegate md, double numOne, double numTwo) { md(numOne, numTwo); }