Beispiel #1
0
        public static void Run()
        {
            Console.WriteLine(nameof(TestCreateDelegate));

            // Ensure things we reflect on are in the static callgraph
            if (string.Empty.Length > 0)
            {
                new Greeter(null).Greet();
                GetHelloInstanceDelegate d  = null;
                Func <Greeter, string>   d2 = d.Invoke;
                d = d2.Invoke;
            }

            TypeInfo   ti = typeof(Greeter).GetTypeInfo();
            MethodInfo mi = ti.GetDeclaredMethod(nameof(Greeter.Greet));
            {
                var d = (GetHelloInstanceDelegate)mi.CreateDelegate(typeof(GetHelloInstanceDelegate));
                if (d(new Greeter("mom")) != "Hello mom")
                {
                    throw new Exception();
                }
            }

            {
                var d = (Func <Greeter, string>)mi.CreateDelegate(typeof(Func <Greeter, string>));
                if (d(new Greeter("pop")) != "Hello pop")
                {
                    throw new Exception();
                }
            }
        }
Beispiel #2
0
    private static int TestCreateDelegate()
    {
        Console.WriteLine("Testing MethodInfo.CreateDelegate");

        // Dummy code to make sure the reflection targets are compiled.
        if (String.Empty.Length > 0)
        {
            new InvokeTests().GetHelloInstance();
            GetHelloInstanceDelegate   d  = null;
            Func <InvokeTests, string> d2 = d.Invoke;
            d = d2.Invoke;
        }

        TypeInfo   ti = typeof(InvokeTests).GetTypeInfo();
        MethodInfo mi = ti.GetDeclaredMethod("GetHelloInstance");

        {
            var d = (GetHelloInstanceDelegate)mi.CreateDelegate(typeof(GetHelloInstanceDelegate));
            if (d(new InvokeTests("mom")) != "Hello mom")
            {
                return(Fail);
            }
        }

        {
            var d = (Func <InvokeTests, string>)mi.CreateDelegate(typeof(Func <InvokeTests, string>));
            if (d(new InvokeTests("pop")) != "Hello pop")
            {
                return(Fail);
            }
        }

        return(Pass);
    }