static void Main(string[] args)
        {
            // Instantiate the delegate.
            Del handler = DelegateMethod;

            // Call the delegate.
            handler("Hello World");            //Hello World

            MethodWithCallback(1, 2, handler); //The number is: 3

            MethodClass obj = new MethodClass();
            Del         d1  = obj.Method1;
            Del         d2  = obj.Method2;
            Del         d3  = DelegateMethod;

            //Both types of assignment are valid.
            Del allMethodsDelegate = d1 + d2;

            allMethodsDelegate += d3;
            //remove Method1
            allMethodsDelegate -= d1;

            // copy AllMethodsDelegate while removing d2
            Del oneMethodDelegate = allMethodsDelegate - d2;

            int invocationCount = d1.GetInvocationList().GetLength(0);
        }
Beispiel #2
0
        public Delegate GetInvocationListPartial(int index)
        {
            Del del = MethodOne;

            del += MethodTwo;
            return(del.GetInvocationList()[index]);
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            Del d = Foo1;

            d += Foo2;
            d += Foo3;
            d += Foo3;
            d += Foo3;
            d += Foo4;
            d += (str) => { Console.WriteLine(str + "I do nothing"); };
            // d("My name is Ivan");
            //    Thread.Sleep(2000);
            //   Console.WriteLine("----------------------------------------");
            d -= Foo2;
            d -= Foo3;
            d -= Foo1;

            d?.Invoke("Ivan");
            //  d("My name is Ivan");

            foreach (Del item in d.GetInvocationList())
            {
                //  Console.WriteLine(item.Method);
                item?.Invoke("Olga");
            }
        }
        //error: A field initalizer cannot reference the nonostatic field, method or property...

        //when we dont put the code below to Test() function we will the error above

        //Because Del is a instance variable, Method1 is a instance method of a instance class
        //there is no guarantee that MethodClass will be initialized before MathodClassTest;

        void Test()
        {
            MethodClass obj = new MethodClass();
            Del         d1  = obj.Method1;
            Del         d2  = obj.Method2;
            Del         d3  = DelegateManager.DelegateMethod;

            //Both types of assignment are valid.
            Del allMethodsDelegate;

            allMethodsDelegate = d1 + d2;

            //multicasting
            allMethodsDelegate(" Called1...");
            //" MethodClass Method1 Called1..."
            //" MethodClass Method2 Called1..."

            allMethodsDelegate += d3;

            //multicasting
            allMethodsDelegate(" Called2....");
            //" MethodClass Method1 Called2..."
            //" MethodClass Method2 Called2..."
            //"DelegateManager DelegateMethod Called2..."

            //remove Method1
            allMethodsDelegate -= d1;
            allMethodsDelegate(" Called3....");
            //" MethodClass Method2 Called2..."
            //"DelegateManager DelegateMethod Called2..."

            int invocationCount = d1.GetInvocationList().GetLength(0);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            Calculate cal = Add;

            Console.WriteLine(cal(5, 5));

            Calculate cal1 = Mutiply;

            Console.WriteLine(cal1(8, 8));

            Console.ReadLine();

            Del d = MethodOne;

            d += MethodTwo;

            d();

            int invocationCount = d.GetInvocationList().GetLength(0);

            Console.WriteLine(invocationCount);

            CovarianceDel Cov = null;

            Cov = MethodStream;
            Cov = MethodString;

            Console.ReadLine();
        }
        public void Test2()
        {
            var obj = new MethodClass();
            Del d1  = obj.Method1;
            Del d2  = obj.Method2;
            Del d3  = DelegateMethod;
            //Both types of assignment are valid.
            Del allMethodsDelegate = d1 + d2;

            allMethodsDelegate += d3;
            int invocationCount = allMethodsDelegate.GetInvocationList().GetLength(0);

            allMethodsDelegate("123");

            var x = ShowMsg == null;

            ShowMsg += ShowName;
            ShowMsg("hahahha");
            var y = ShowMsg == null;


            //Delegate1 d;
            //Delegate2 e; System.Delegate f;
            // Console.WriteLine(d==e);
            //Console.WriteLine(d==f);
        }
        protected override void UseSample()
        {
            Del del = MethodOne;

            del += MethodTwo;
            Logger.Info($"Delegate invocation list consists of {del.GetInvocationList().GetLength(0)} elements");
            del();
        }
Beispiel #8
0
        public void Run()
        {
            Del d = MethodOne;

            d += MethodTwo;
            d();

            Console.WriteLine(d.GetInvocationList().GetLength(0));
        }
        public void MulticastDelegate()
        {
            Del d = MethodOne;

            d += MethodTwo;

            d();

            Console.WriteLine("No. of methods that will be called = {0}", d.GetInvocationList().GetLength(0));
        }
Beispiel #10
0
        private static void Multicast()
        {
            Del d = MethodOne;

            d += MethodTwo;

            d();
            var invocationCount = d.GetInvocationList().Count();

            Console.WriteLine("d invocation count is: {0}", invocationCount);
        }
Beispiel #11
0
        // a multicast delegate
        public static void Main(string[] args)
        {
            Del del = MethodOne;

            del += MethodTwo;

            del();

            Console.WriteLine(del.GetInvocationList().GetLength(0));
            Console.ReadKey();
        }
        public static void Multicast()
        {
            Del d = MethodOne;

            d += MethodTwo;
            d();

            int invocationCount = d.GetInvocationList().GetLength(0);

            Console.WriteLine(invocationCount);
        }
        public void MulticastingDelegates()
        {
            Del d = MethodOne;

            d += MethodTwo;

            d();

            int invocationCount = d.GetInvocationList().GetLength(0);

            Console.WriteLine("Methods invoked by delegate: {0}", invocationCount);
        }
Beispiel #14
0
        public void Multicast()
        {
            Del d = MethodOne;

            d += MethodTwo;
            Delegate[] list  = d.GetInvocationList();
            int        count = list.GetLength(0);

            Console.WriteLine($"count 1: {list.Count()} ");
            Console.WriteLine($"count 2: {count} ");
            d();
        }
Beispiel #15
0
        public void Empezar()
        {
            //creamos un objeto delegado
            Del del = Escribir; //Le asignamos el metodo escribir sin necesidad de los parametros

            // Del del = new Del(Escribir);//otra forma de crear el obj del
            del("texto desde el programa principal");//LLamamos al delegado y pasamos el parametro como texto


            //tambien se puede enviar delegados como parametros
            MethodWithCallback(1, 2, del);//El metodo acepta un delegado, le pasamos del creado anteriormente

            //Se puede crear un delegados con varias delegados
            MethodClass obj = new MethodClass(); //Creamos un obj de la clase con dos metodos
            Del         d1  = obj.Method1;       //creamos un delegado llamado d1
            Del         d2  = obj.Method2;       //creamos un delegado llamado d1

            //Both types of assignment are valid.
            Del allMethodsDelegate = d1 + d2;

            allMethodsDelegate += del;

            //se puede llamar al método que te dice cuantos delegados tiene el obj
            int invocationCount = allMethodsDelegate.GetInvocationList().GetLength(0);

            Console.WriteLine("El delegado allmethodsDelegate tiene  " + invocationCount + " delegados");

            allMethodsDelegate("all methods");

            //Si el delegado usa parámetros de referencia, la referencia se pasa secuencialmente a cada uno
            //    de los tres métodos por turnos, y cualquier cambio que realice un método es visible para el
            //    siguiente método. Cuando alguno de los métodos produce una excepción que no se captura dentro
            //    del método, esa excepción se pasa al llamador del delegado y no se llama a los métodos siguientes
            //    de la lista de invocación.Si el delegado tiene un valor devuelto o los parámetros de salida,
            //    devuelve el valor devuelto y los parámetros del último método invocado. Para quitar un método
            //    de la lista de invocación, utilice el operador de decremento o el operador de asignación de
            //    decremento('-' o '-= '). Por ejemplo:
            //remove Method1
            allMethodsDelegate -= d1;

            // copy AllMethodsDelegate while removing d2
            Del oneMethodDelegate = allMethodsDelegate - d2;


            // Crear un delegado con un metodo anónimo.
            Del del3 = delegate(string name)
            { Console.WriteLine("Notification received for: {0}", name); };

            //Crear un delegado con una expresión lambda.
            Del del4 = name => { Console.WriteLine("Notification received for: {0}", name); };

            del4("del 4");
        }
Beispiel #16
0
        public static void RunMain()
        {
            Del d = MethodOne;

            d += MethodTwo;

            d();

            int invoactionCount = d.GetInvocationList().GetLength(0);

            Console.WriteLine($" invoactionCount : {invoactionCount}");
        }
Beispiel #17
0
        public static void MulticastDelegate()
        {
            Del d = Metodo1;

            d += Metodo2;

            int invocationCount = d.GetInvocationList().GetLength(0);

            Console.WriteLine(invocationCount);

            d();
        }
Beispiel #18
0
        internal static void MultiCastingDelegates()
        {
            Del d = MethodOne;

            // Add subsequent methods to invocation list.
            d += MethodTwo;

            int invocationCount = d.GetInvocationList().GetLength(0);

            Console.WriteLine($"No. of methods in the invocationlist {invocationCount}");

            d();
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            UseDelegate();

            //A multicast delegate
            Del d = MethodOne;

            d += MethodTwo;
            d();
            int invocationCount = d.GetInvocationList().GetLength(0); // how many methods a multicast delegate is going to cal

            Console.WriteLine(invocationCount);
            UseCovariance();
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            // Instantiate the delegate.
            Del handler = DelegateMethod;

            // Call the delegate.
            handler("Hello World");
            MethodWithCallback(1, 2, handler);

            // A delegate can call more than one method when invoked. This is referred to as multicasting.
            // To add an extra method to the delegate's list of methods—the invocation list—simply requires
            // adding two delegates using the addition or addition assignment operators ('+' or '+=').
            var obj = new MethodClass();
            Del d1  = obj.Method1;
            Del d2  = obj.Method2;
            Del d3  = DelegateMethod;

            //Both types of assignment are valid.
            Del allMethodsDelegate = d1 + d2;

            allMethodsDelegate += d3;
            allMethodsDelegate("multicasting message");

            // At this point allMethodsDelegate contains three methods in its invocation list—Method1, Method2, and DelegateMethod.
            // The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all
            // three methods are called in order. If the delegate uses reference parameters, the reference is passed
            // sequentially to each of the three methods in turn, and any changes by one method are visible to the next method.
            // When any of the methods throws an exception that is not caught within the method, that exception is passed
            // to the caller of the delegate and no subsequent methods in the invocation list are called. If the delegate
            // has a return value and/or out parameters, it returns the return value and parameters of the last method invoked.
            // To remove a method from the invocation list, use the subtraction or subtraction assignment operators (- or -=).

            // remove Method1
            allMethodsDelegate -= d1;
            // copy AllMethodsDelegate while removing d2
            Del oneMethodDelegate = allMethodsDelegate - d2;

            // Because delegate types are derived from System.Delegate, the methods and properties defined by that class
            // can be called on the delegate. For example, to find the number of methods in a delegate's invocation list, you may write:
            int invocationCount = d1.GetInvocationList().GetLength(0);

            // Delegates with more than one method in their invocation list derive from MulticastDelegate, which is a subclass of System.Delegate.

            // Multicast delegates are used extensively in event handling. Event source objects send event notifications to
            // recipient/ objects that have registered to receive that event. To register for an event, the recipient creates
            // a method designed to handle the event, then creates a delegate for that method and passes the delegate to the
            // event source. The source calls the delegate when the event occurs. The delegate then calls the event handling
            // method on the recipient, delivering the event data. The delegate type for a given event is defined by the event source.
        }
Beispiel #21
0
        public static void Test()
        {
            MethodClass methodClass = new MethodClass();
            Del         del1        = DeleteMethod;
            Del         del2        = methodClass.Method1;
            Del         del3        = methodClass.Method2;


            Del handler = del1 + del2 + del3;

            handler("Hello World");

            Console.WriteLine($"委托数量:{handler.GetInvocationList().Length}");
            Console.WriteLine($"是否同一委托:{del1 == del2}");
        }
Beispiel #22
0
        public void Ex2_Multicast()
        {
            Del d = new Del(() =>
            {
                Console.WriteLine("MethodOne");
                return(1);
            });

            d  = d + this.Method2;
            d += () =>
            {
                Console.WriteLine("MethodThree");
                return(3);
            };

            Console.WriteLine("Count: {0}", d.GetInvocationList().GetLength(0));
            d -= this.Method2; // removes delegate

            Console.WriteLine("Count: {0}", d.GetInvocationList().GetLength(0));

            int r = d(); // invokes group

            Console.WriteLine("Return: {0}", r);
        }
Beispiel #23
0
        // A multicast delegate
        public MainListing1X76()
        {
            Del d = MethodOne;

            d += MethodTwo;

            d();

            // Também é possível remover métodos de uma lista de métodos
            // usando o decrementador - ou -=

            // Para saber quantos métodos existem em um delegate
            int invocationCount = d.GetInvocationList().GetLength(0);

            Console.WriteLine(invocationCount);
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            Del d = MethodOne;

            d += MethodTwo;
            d += MethodThree;

            d -= MethodOne; //One will be removed

            //Find How many methods delegate gonna call
            int methodCount = d.GetInvocationList().Count();

            Console.WriteLine("Delegate will call {0} methods", methodCount);

            d();


            Console.ReadLine();
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            Del d = MethodOne;

            //adiciona mais um metodo ao delegate
            d += MethodTwo;
            //chama todos os metedos adicionados ao delegate
            d();
            //remove o metodo da lista, caso não exista esse metodo no delegate ele não irá retorna um exception
            d -= MethodOne;
            d();

            d += MethodOne;
            //Pega quantidade de metodo que está no delegate
            int count = d.GetInvocationList().GetLength(0);

            Console.WriteLine(count);

            Console.Read();
        }
Beispiel #26
0
        //Along with the static DelegateMethod shown previously, we now have three methods that can be wrapped by a Del instance.
        public void exampleForInstanceMethod()
        {
            MethodClass obj = new MethodClass();
            Del         d1  = obj.Method1;
            Del         d2  = obj.Method2;
            Del         d3  = DelegateMethod;

            //Both types of assignment are valid.
            Del allMethodsDelegate = d1 + d2;

            allMethodsDelegate += d3;

            //At this point allMethodsDelegate contains three methods in its invocation list—Method1, Method2, and DelegateMethod.
            //The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order.
            //If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn,
            //and any changes by one method are visible to the next method.
            //When any of the methods throws an exception that is not caught within the method,
            //that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called.
            //If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked.
            //To remove a method from the invocation list, use the decrement or decrement assignment operator ('-' or '-='). For example:

            //remove Method1
            allMethodsDelegate -= d1;

            // copy AllMethodsDelegate while removing d2
            Del oneMethodDelegate = allMethodsDelegate - d2;

            //Because delegate types are derived from System.Delegate, the methods and properties defined by that class can be called on the delegate.
            //For example, to find the number of methods in a delegate's invocation list, you may write:
            int invocationCount = d1.GetInvocationList().GetLength(0);

            //Comparing delegates of two different types assigned at compile-time will result in a compilation error.
            //If the delegate instances are statically of the type System.Delegate, then the comparison is allowed, but will return false at run time. For example:
            // Compile-time error.
            //Console.WriteLine(d1 == e2);

            // OK at compile-time. False if the run-time type of f
            // is not the same as that of d.
            System.Console.WriteLine(d1 == d2);
        }
Beispiel #27
0
        static void Main(string[] args)
        {
            Del handler = DelegateMethod;

            handler("DelegateMethod");
            MethodWithCallback(1, 2, handler);

            MethodClass obj = new MethodClass();
            Del         d1  = obj.Method1;
            Del         d2  = obj.Method2;
            Del         d3  = DelegateMethod;

            Del allMethodDelegate = d1 + d2;

            allMethodDelegate += d3;

            allMethodDelegate -= d1;

            Del oneMethodDelegate = allMethodDelegate - d2;

            int invocationCount = d1.GetInvocationList().GetLength(0);
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            #region MyRegion
            Del handler = DelegateMethod;
            handler("Hello");

            MethodWithCallback(1, 2, handler);
            MethodWithCallback(3, 4, handler);
            MethodWithCallback(5, 6, handler);

            MethodClass obj  = new MethodClass();
            Del         d1_1 = obj.Metrhod1;
            Del         d1_2 = obj.Metrhod2;
            Del         d1_3 = DelegateMethod;

            Del allMethodsDelegate = d1_1 + d1_2;
            allMethodsDelegate += d1_3;
            int invocationCount = allMethodsDelegate.GetInvocationList().Length;//.GetLength(0);
            Console.WriteLine($"count:{invocationCount}");

            Del2 d2 = obj.MultipyNumbers;
            Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
            for (int i = 1; i <= 5; i++)
            {
                d2(i, 2);
            }

            Console.WriteLine("委托映射到静态方法和实例方法,并返回来自两种方法的具体信息:");
            Del3 d3_1 = obj.InstancaMethod;
            d3_1();
            Del3 d3_2 = MethodClass.StaticMethod;
            d3_2();

            Console.WriteLine("multicast delegates(多播委托):");
            CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;
            hiDel           = Hello;
            byeDel          = Goodbye;
            multiDel        = hiDel + byeDel;
            multiMinusHiDel = multiDel - hiDel;
            Console.WriteLine("Invoke delegate hiDel:");
            hiDel("A");
            Console.WriteLine("Invoke delegate byDel:");
            byeDel("B");
            Console.WriteLine("Invoke delegate multiDel:");
            multiDel("C");
            Console.WriteLine("Invoke delegate multiMinusHiDel:");
            multiMinusHiDel("D");
            #endregion

            #region Func Delegate
            Console.WriteLine("\nFunc Delegate:\n");

            OutPutTarget output = new OutPutTarget();
            // 调用自定义委托:WriteMethod
            //WriteMethod methodCall = output.SendToFile;
            // 调用Func<TResult>
            //Func<bool> methodCall = output.SendToFile;
            // 使用 Func<TResult> 委托与 C# 中的匿名方法
            //Func<bool> methodCall = delegate () { return output.SendToFile(); };
            // lambda 表达式 Func<T, TResult> 委托
            Func <bool> methodCall = () => output.SendToFile();
            if (methodCall())
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("File write operation failed");
            }

            Console.WriteLine("\nFunc Delegate示例:\n");
            LazyValue <int>  lazyOne = new LazyValue <int>(() => ExpensiveOne());
            LazyValue <long> lazyTwo = new LazyValue <long>(() => ExpensiveTwo("hello"));
            Console.WriteLine("LazyValue objects has been created.");
            Console.WriteLine(lazyOne.Value);
            Console.WriteLine(lazyTwo.Value);
            #endregion

            #region Func<T1, T2, TResult> 委托
            Console.WriteLine("Func<T1, T2, TResult> 委托:");
            Func <string, int, bool> predicate = (str, index) => str.Length == index;
            string[]             words         = { "orange", "apple", "Article", "elephant", "star", "and" };
            IEnumerable <string> aWords        = words.Where(predicate).Select(str => str);
            foreach (string word in aWords)
            {
                Console.WriteLine(word);
            }

            #endregion
        }