public DelegateClass() { Transformer tr = new Transformer(Square); // 3a) Create delegate instance Transformer t = Square; // 3b SHORTCUT) Create delegate instance (assigning a method to a delegate variable) //Square = method group (without brackets or arguments). If overloaded, C# will pick the correct overload based on the signature of the delegate int resultr = tr.Invoke(3); //4a) Invoke delegate int result = t(3); // 4b SHORTCUT) Invoke delegate //Caller invokes the delegate, and then the delegate calls the target method. //This indirection decouples the caller from the target method. Console.WriteLine(result); // 9 //Perform method calls in the order they have been added to delegate Transformer tmulti = null; tmulti += Square; tmulti += SquareAndAdd; tmulti -= Square; int[] squareNumbers = { 1, 2, 3, 4 }; int[] squareResult = SquareNumber(squareNumbers, Square); Console.WriteLine(string.Concat(squareResult)); //Delegate types are all incompatible each others Trans1 tr1 = Square; Trans2 tr2 = new Trans2(tr1); //It works! //Trans2 tr2 = tr1; //Doesn't works! Compile-time error tr2(3); Console.WriteLine(string.Concat(tr.Method.ToString())); Console.WriteLine(string.Concat(t.Method.ToString())); //Possibile assignement with more generic argument type (object rather than string) -> Contravariance TransObj tobj = new TransObj(SquareObj); //Possible method return type more specific than delegate return type -> Covariance TransObjRet tobjret = SquareObjRet; object stringResult = tobjret(); }
public R( Single1 single1, Single2 single2, Scoped1 scoped1, Scoped2 scoped2, Trans1 trans1, Trans2 trans2, ScopedFac1 scopedFac1, ScopedFac2 scopedFac2, SingleObj1 singleObj1, SingleObj2 singleObj2 ) { Single1 = single1; Single2 = single2; Scoped1 = scoped1; Scoped2 = scoped2; Trans1 = trans1; Trans2 = trans2; ScopedFac1 = scopedFac1; ScopedFac2 = scopedFac2; SingleObj1 = singleObj1; SingleObj2 = singleObj2; }