static void Main(string[] args)
        {
            //instance
            Program p = new Program();

            p.AddNums(1, 2);

            //static
            Console.WriteLine(Program.StringHello("arun"));

            //2
            AddDelegate addDelegate = new AddDelegate(p.AddNums);
            SayDelegate sayDelegate = new SayDelegate(StringHello);


            Console.WriteLine("Delegates");
            addDelegate(2, 4);
            addDelegate.Invoke(10, 20);
            Console.WriteLine(sayDelegate("ARUN"));
            Console.WriteLine(sayDelegate.Invoke("Arun"));


            Console.WriteLine("Multi cast delegates");
            HelloDelegate helloDelegate = p.SayHello;

            helloDelegate += p.SayHelloWorld;
            helloDelegate();
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            HelloDelegate helloDelegate = new HelloDelegate(helo);

            helloDelegate("Hello fom delegta");
            //int Number = 11;
            //bool isNumber10 = (Number == 10 ? true : false);
            //Console.WriteLine("isNumber10 is {0}", isNumber10);
            //A objA = new A();
            //objA.functionFromA();
            //B objB = new B();
            //objB.functionFromA();
            //A obj2 = new B();
            //obj2.functionFromA();
            //B obj3 = new B();
            //((A)obj3).functionFromA();
            //A obj4 = new B();
            //obj4.polymor();
            //A obj5 = new C();
            //obj5.polymor();
            //Program p = new Program();
            //Program p2 = new Program();
            //p2.functinfromI();
            //((I)p).functinfromI();
            //((I2)p).functinfromI();
            //Program p = new Program();
            //p.absPrint2();
        }
Esempio n. 3
0
        public static void Hello()
        {
            try
            {
                //定义一个名字为HelloWorld的动态方法,没有返回值,没有参数
                DynamicMethod helloMethod = new DynamicMethod("HelloWorld", null, null);
                //创建MSIL生成器,为动态方法生成代码
                ILGenerator iLGenerator = helloMethod.GetILGenerator();
                //将动态方法需要输出的字符串Hello World! 添加到堆栈上
                iLGenerator.Emit(OpCodes.Ldstr, "Hello World@");
                //调用输出方法输出字符串
                iLGenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
                //方法结束
                iLGenerator.Emit(OpCodes.Ret);
                //完成动态方法的创建,并且获取一个可以执行该动态方法的委托
                HelloDelegate hello = (HelloDelegate)helloMethod.CreateDelegate(typeof(HelloDelegate));

                // 执行动态方法,将在屏幕上打印Hello World!
                hello();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Esempio n. 4
0
        delegate bool IsEqual(int x);           // Для примера 6

        static void Main()
        {
            /* Пример 1*/

            Console.WriteLine("Пример 1: ");
            /* (x, y) => x + y; Лямбда-выражение, где x и y - это параметры, а x + y - выражение*/
            Operation operation = (x, y) => x + y;  // создаём делегат с лямбда выражением

            Console.WriteLine(operation(10, 20));   // 30
            Console.WriteLine(operation(40, 20));   // 60

            /* Пример 2*/

            Console.WriteLine("Пример 2: ");
            /* Если лямбда-выражение принимает один параметр, то скобки вокруг параметра можно опустить: */
            Square square = i => i * i;
            int    z      = square(6);

            Console.WriteLine(z);                   //36

            /* Пример 3 */

            Console.WriteLine("Пример 3: ");
            /* Если параметры не требуются, то в лямбда выражениях используются пустые скобки*/
            Hello hello1 = () => Console.WriteLine("Hello");
            Hello hello2 = () => Console.WriteLine("Welcome");

            hello1();                               // Hello
            hello2();                               // Welcome

            /* Пример 4 */

            Console.WriteLine("Пример 4: ");
            /* Обязательно нужно указывать тип, если делегат имеет параметры с модификаторами ref и out */
            int           j             = 9;
            ChangeHandler changeHandler = (ref int m) => m = m * 2;

            changeHandler(ref j);
            Console.WriteLine(j);                   // 18

            /* Пример 5 */

            Console.WriteLine("Пример 5: ");
            /* Лямбда выражения таже могут выполнять другие методы*/
            HelloDelegate helloDelegate = () => Show_Message();

            helloDelegate();

            /* Пример 6: */

            Console.WriteLine("Пример 6: ");
            /* Лямбды можно передавать в качестве аргументов методу для тех параметров, которые представляют делегат */
            int[] integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int   result1  = Sum(integers, x => x > 5);

            Console.WriteLine(result1);              // 30
            int result2 = Sum(integers, x => x % 2 == 0);

            Console.WriteLine(result2);              // 20
        }
Esempio n. 5
0
        //public static void Addnum(int a, int b)
        //{
        //    Console.WriteLine(a + b);
        //}
        static void Main(string[] args)
        {
            // AddnumDelegate obj = new AddnumDelegate(Addnum);
            AddnumDelegate obj1 = delegate(int a, int b)
            {
                Console.WriteLine(a + b);
            };
            // obj.Invoke("Girls");
            // Console.WriteLine(obj.Invoke("Girls"));
            mulDelegate obj = delegate(int a, int b)
            {
                Console.WriteLine(a * b);
            };
            divDelegate obj2 = delegate(int a, int b)
            {
                Console.WriteLine(a / b);
            };
            HelloDelegate obj3 = delegate(string name)
            {
                Console.WriteLine("The name is: " + name);
            };

            obj1.Invoke(10, 20);
            obj.Invoke(15, 30);
            obj2.Invoke(30, 15);
            obj3.Invoke("kavya");
            Console.ReadKey();
        }
    static void Main(string[] args)
    {
        HelloDelegate hello1 = new HelloDelegate(SayHello);

        hello1 += new HelloDelegate(SayHello2);
        hello1();
    }
        static void Main(string[] args)
        {
            HelloDelegate hd = delegate(string greet)
            {
                Console.WriteLine(greet);
            };

            hd.Invoke("Good Morning!!");
            AddDelegate ad = delegate(double val1, double val2)
            {
                Console.WriteLine(val1 + val2);
            };

            ad.Invoke(123.3446, 2343.44466);
            subDelegate sd = delegate(double val1, double val2)
            {
                Console.WriteLine(val1 - val2);
            };

            sd.Invoke(365.35356, 123.43454);
            MultiplyDelegate md = delegate(int val1, int val2)
            {
                Console.WriteLine(val1 * val2);
            };

            sd.Invoke(125, 132);
            Console.ReadKey();
        }
 static void Main(string[] args){
   // C# 1.0
   Delegate10 del10 = new Delegate10(StaticHello);
   del10("This function create new delegatetion of C#.0");
   // C#2.0
   Delegate10 del20 = StaticHello;
   del20("C#2.0からデリゲートの作成はnew演算子を使わなくでも代入できるのだ!");
   
   var foo = new Foo();
   // Declare delegate
   HelloDelegate funcs;
   funcs = foo.Hello;
   funcs += StaticHello;
   // C#3.0 lambda Expresstion
   funcs += (string name) => {
     Console.WriteLine("(lambda) : Hello {0}",name);
   };
   // C#3.0 組込delegate型
   Action<string> tlambda = str => { Console.WriteLine(str);};
   // Castting To HelloDelegate 
   funcs += new HelloDelegate( tlambda);
   // NG : funcs += (HelloDelegate) tlambda;
   //型推論で省略できる。
   funcs += str => {Console.WriteLine(str);};
   // C#2.0 Anonymouse Method
   funcs += delegate(string name){
     Console.WriteLine("(delegate) : Hello {0}",name);
   };
   funcs("World");
   }
Esempio n. 9
0
        static void Main(string[] args)
        {
            HelloDelegate hD = () => Console.WriteLine("Hello!");

            hD();

            Console.ReadKey();
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            HelloDelegate hD = (x) => { Console.WriteLine("Привет, " + x); };

            hD("Вася");

            Console.ReadKey();
        }
Esempio n. 11
0
    static void Main(string[] args)
    {
        HelloDelegate hello1 = new HelloDelegate(SayHello);

        hello1 += new HelloDelegate(SayHello2);
        //hello1 += SayHello2;
        Test(hello1);
    }
Esempio n. 12
0
    static void Main(string[] args)
    {
        HelloDelegate hello1 = new HelloDelegate(SayHello);
        HelloDelegate hello2 = SayHello;

        hello1.Invoke();
        hello2.Invoke();
        hello1();
    }
Esempio n. 13
0
    static void Main(string[] args)
    {
        HelloDelegate hello1 = new HelloDelegate(SayHello);

        hello1 += SayHello2;
        hello1();
        Sample        sam    = new Sample();
        HelloDelegate hello3 = sam.SayHello;

        Test(hello3);
    }
Esempio n. 14
0
        static void Main(string[] args)
        {
            SomeClass someClass = new SomeClass();

            HelloDelegate hD = new HelloDelegate(someClass.SayHello);

            Console.WriteLine(hD.Invoke("Вася"));

            Console.WriteLine(hD("Вася"));

            Console.ReadKey();
        }
Esempio n. 15
0
        private static void Main(string[] args)
        {
            HelloDelegate del = new HelloDelegate(Hello);

            del += Test;
            del += Test;
            del += Test;
            del += Test;
            del -= Hello;

            del("Hello from delegate");
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            HelloDelegate obj = delegate(string val)
            {
                return("Hello " + val + "!");
            };

            string str = obj.Invoke("Mubashir");

            Console.WriteLine(str);

            Console.ReadLine();
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            Program     p = new Program();
            AddDelegate a = new AddDelegate(p.Add);

            a.Invoke(10, 10);

            HelloDelegate h   = new HelloDelegate(Hello);
            string        str = h.Invoke("swamy");

            Console.WriteLine(str);
            Console.ReadLine();
        }
Esempio n. 18
0
    static void Main(string[] args)
    {
        HelloDelegate hello1 = new HelloDelegate(SayHello);
        HelloDelegate hello2 = SayHello;

        hello1.Invoke();
        hello2.Invoke();
        hello1();
        Test(hello1);

        hello1 += SayHello;

        Sample        sam    = new Sample();
        HelloDelegate hello3 = sam.SayHello;

        sam();
    }
Esempio n. 19
0
        static void Main()
        {
            Foo foo = new Foo();

            // delegate の変数
            HelloDelegate funcs = delegate(string name){};

            funcs += foo.Hello;         // メソッドの格納
            funcs += StaticHello;       // static 関数の格納
            // 無名関数の格納
            funcs += (string name) => {
                Console.WriteLine("(lambda) : Hello {0}!", name);
            };
            // 無名関数の格納 (delegete キーワード版)
            funcs += delegate(string name) {
                Console.WriteLine("(delegate) : Hello {0}!", name);
            };

            // 格納した関数の呼び出し
            funcs("world");
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();

            // 指定委派物件到一個執行個體上的方法(函式簽章需要相同)
            HelloDelegate helloDelegate = myClass.SayHelloInstance;

            // 直接執行該委派物件上指定的物件方法,
            // 也就是呼叫 MyClass.SayHelloInstance
            helloDelegate("Vulcan");
            // 使用委派的 Invoke 方法來同步呼叫此方法
            helloDelegate.Invoke("Vulcan");

            // 指定委派物件到一個靜態方法(函式簽章需要相同)
            helloDelegate = new HelloDelegate(MyClass.SayHelloStatic);
            // 直接執行該委派物件上指定的靜態方法,
            // 也就是呼叫 MyClass.SayHelloStatic
            helloDelegate("Ada");
            // 使用委派的 Invoke 方法來同步呼叫此方法
            helloDelegate.Invoke("Ada");

            Console.WriteLine("Press any key for continuing...");
            Console.ReadKey();
        }
Esempio n. 21
0
 static void Test(HelloDelegate del)
 {
     del();
 }
Esempio n. 22
0
    public static void Main()
    {
        HelloDelegate del = new HelloDelegate(Hello);

        del("Confusing delegate");
    }
Esempio n. 23
0
 static void Main(string[] args)
 {
     HelloDelegate del = new HelloDelegate(Hello);
     del("this is the message");
 }
Esempio n. 24
0
    public static void Main()
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This dynamic method has a String
        // parameter and an Integer parameter.
        Type[] helloArgs = { typeof(string), typeof(int) };

        // Create a dynamic method with the name "Hello", a return type
        // of Integer, and two parameters whose types are specified by
        // the array helloArgs. Create the method in the module that
        // defines the String class.
        DynamicMethod hello = new DynamicMethod("Hello",
                                                typeof(int),
                                                helloArgs,
                                                typeof(string).Module);

        // <Snippet2>
        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type[] writeStringArgs = { typeof(string) };
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString = typeof(Console).GetMethod("WriteLine",
                                                           writeStringArgs);

        // Get an ILGenerator and emit a body for the dynamic method,
        // using a stream size larger than the IL that will be
        // emitted.
        ILGenerator il = hello.GetILGenerator(256);

        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ret);
        // </Snippet2>

        // <Snippet33>
        // Add parameter information to the dynamic method. (This is not
        // necessary, but can be useful for debugging.) For each parameter,
        // identified by position, supply the parameter attributes and a
        // parameter name.
        hello.DefineParameter(1, ParameterAttributes.In, "message");
        hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn");
        // </Snippet33>

        // <Snippet3>
        // Create a delegate that represents the dynamic method. This
        // action completes the method. Any further attempts to
        // change the method are ignored.
        HelloDelegate hi =
            (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));

        // Use the delegate to execute the dynamic method.
        Console.WriteLine("\r\nUse the delegate to execute the dynamic method:");
        int retval = hi("\r\nHello, World!", 42);

        Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned: " + retval);

        // Execute it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) returned: " + retval);
        // </Snippet3>

        // <Snippet4>
        Console.WriteLine("\r\nUse the Invoke method to execute the dynamic method:");
        // Create an array of arguments to use with the Invoke method.
        object[] invokeArgs = { "\r\nHello, World!", 42 };
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and value-type arguments
        // must be boxed.
        object objRet = hello.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));

        Console.WriteLine("hello.Invoke returned: " + objRet);
        // </Snippet4>

        Console.WriteLine("\r\n ----- Display information about the dynamic method -----");
        // <Snippet21>
        // Display MethodAttributes for the dynamic method, set when
        // the dynamic method was created.
        Console.WriteLine("\r\nMethod Attributes: {0}", hello.Attributes);
        // </Snippet21>

        // <Snippet22>
        // Display the calling convention of the dynamic method, set when the
        // dynamic method was created.
        Console.WriteLine("\r\nCalling convention: {0}", hello.CallingConvention);
        // </Snippet22>

        // <Snippet23>
        // Display the declaring type, which is always null for dynamic
        // methods.
        if (hello.DeclaringType == null)
        {
            Console.WriteLine("\r\nDeclaringType is always null for dynamic methods.");
        }
        else
        {
            Console.WriteLine("DeclaringType: {0}", hello.DeclaringType);
        }
        // </Snippet23>

        // <Snippet24>
        // Display the default value for InitLocals.
        if (hello.InitLocals)
        {
            Console.Write("\r\nThis method contains verifiable code.");
        }
        else
        {
            Console.Write("\r\nThis method contains unverifiable code.");
        }
        Console.WriteLine(" (InitLocals = {0})", hello.InitLocals);
        // </Snippet24>

        // <Snippet26>
        // Display the module specified when the dynamic method was created.
        Console.WriteLine("\r\nModule: {0}", hello.Module);
        // </Snippet26>

        // <Snippet27>
        // Display the name specified when the dynamic method was created.
        // Note that the name can be blank.
        Console.WriteLine("\r\nName: {0}", hello.Name);
        // </Snippet27>

        // <Snippet28>
        // For dynamic methods, the reflected type is always null.
        if (hello.ReflectedType == null)
        {
            Console.WriteLine("\r\nReflectedType is null.");
        }
        else
        {
            Console.WriteLine("\r\nReflectedType: {0}", hello.ReflectedType);
        }
        // </Snippet28>

        // <Snippet29>
        if (hello.ReturnParameter == null)
        {
            Console.WriteLine("\r\nMethod has no return parameter.");
        }
        else
        {
            Console.WriteLine("\r\nReturn parameter: {0}", hello.ReturnParameter);
        }
        // </Snippet29>

        // <Snippet30>
        // If the method has no return type, ReturnType is System.Void.
        Console.WriteLine("\r\nReturn type: {0}", hello.ReturnType);
        // </Snippet30>

        // <Snippet31>
        // ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
        // that can be used to enumerate the custom attributes of the
        // return value. At present, there is no way to set such custom
        // attributes, so the list is empty.
        if (hello.ReturnType == typeof(void))
        {
            Console.WriteLine("The method has no return type.");
        }
        else
        {
            ICustomAttributeProvider caProvider = hello.ReturnTypeCustomAttributes;
            object[] returnAttributes           = caProvider.GetCustomAttributes(true);
            if (returnAttributes.Length == 0)
            {
                Console.WriteLine("\r\nThe return type has no custom attributes.");
            }
            else
            {
                Console.WriteLine("\r\nThe return type has the following custom attributes:");
                foreach (object attr in returnAttributes)
                {
                    Console.WriteLine("\t{0}", attr.ToString());
                }
            }
        }
        // </Snippet31>

        // <Snippet32>
        Console.WriteLine("\r\nToString: {0}", hello.ToString());
        // </Snippet32>

        // <Snippet34>
        // Display parameter information.
        ParameterInfo[] parameters = hello.GetParameters();
        Console.WriteLine("\r\nParameters: name, type, ParameterAttributes");
        foreach (ParameterInfo p in parameters)
        {
            Console.WriteLine("\t{0}, {1}, {2}",
                              p.Name, p.ParameterType, p.Attributes);
        }
        // </Snippet34>
    }