예제 #1
0
        static void Main(string[] args)
        {
            SingleDelegate d1 = new SingleDelegate();
            // d1.sum(10, 20);
            //Console.WriteLine(Delegate1.Program(" " + "Amar"));
            //2.instantiating the delegating
            SumDelegate sd = new SumDelegate(d1.sum);

            sd(100, 200); //passing the required parameter and calling the delegate
            sd.Invoke(200, 300);


            ProgramDelegate pd = new ProgramDelegate(Program);

            Console.WriteLine(pd("Amar"));
            Console.WriteLine(pd.Invoke("Ram"));

            MulDelegate md = new MulDelegate(d1.Mul); //non-static method call by ref of instance class

            Console.WriteLine("Mul:" + md(10, 2));

            DivDelegate dv = new DivDelegate(Div);

            Console.WriteLine("Div:" + dv(100, 2));

            Console.Read();
        }
예제 #2
0
    public static void Main()
    {
        Type[] methodArgs = { typeof(Example), typeof(int) };

        DynamicMethod dm = new DynamicMethod(
            "",
            typeof(int),
            methodArgs,
            typeof(Example));


        ILGenerator il = dm.GetILGenerator();

        // Console.WriteLine function in the msil. Can be used as il.EmitCall(OpCodes.Call, writeString, null);
        // Type[] writeStringArgs = {typeof(string)};
        // MethodInfo writeString = typeof(Console).GetMethod("WriteLine",
        //     writeStringArgs);

        // Local variable declaration
        // LocalBuilder a = il.DeclareLocal(typeof(Int32));

        // Field declaration
        // FieldInfo testInfo = typeof(Example).GetField("test",
        //     BindingFlags.NonPublic | BindingFlags.Instance);

        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldc_I4, 3);
        il.Emit(OpCodes.Mul);
        il.Emit(OpCodes.Ret);

        ProgramDelegate invoke =
            (ProgramDelegate)dm.CreateDelegate(typeof(ProgramDelegate));

        // Pass argument 14 to the Ldarg_1 of MSIL function
        Console.WriteLine("3 * test = {0}", invoke(14));
    }