1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Program { public delegate bool D(); public delegate bool D2(int i); class Test { D del; //private, no accessible public D2 del2; //public, accessible // method public void TestMethod(int input) { //method scope Console.WriteLine("TestMethod start"); int j = 0; //delegate definition in method //has access to outer scope del = () => { Console.WriteLine("del delegate definition start"); j = 10; return j > input; }; //accesses outer scope int j and input del2 = (x) => { Console.WriteLine("del2 delegate definition start"); // x is passed in as parameter // j is declared outside scope. // input was passed in earlier Console.WriteLine("x is {0}, j is {1} input is {2}", x, j, input); return x == j; }; Console.WriteLine("j = {0}", j); bool boolResult = del(); //j is local scope Console.WriteLine("j = {0}. b = {1}", j, boolResult); } } public static void Main() { Test test = new Test(); test.TestMethod(5); //delegate del2, still has copy of local varaibles j and input from TestMethod. bool boolResult = test.del2(10); Console.WriteLine(boolResult); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System; public class Program { // declare the delegate delcaration // it takes an int as a parameter // it returns an int public delegate int DelType(int i); // we are a static object, thus, methods must match static status public static void displayMagicNumber(DelType dd) { Console.WriteLine("{0}", dd(886)); } public static void Main() { // declare a delegate variable // assign it to a delegate definiton // where it takes and returns an int DelType dd = delegate(int value) { return (value +2); }; Console.WriteLine("{0}", dd(10)); displayMagicNumber(dd); } } |