vendredi 24 avril 2020

Invoke a method with reflection

I would like to create a method that takes an unspecified object as an argument and uses its methods.

using System;
using System.Reflection;

namespace TestReflection
{
    class Program
    {
        static void Main(string[]args)
        {
            Test t1 = new Test
            {
                A = 2,
                B = "test"
            };

            Program p = new Program();
            Console.WriteLine("\nNormal");
            Console.WriteLine("A: {0}", t1.A);
            Console.WriteLine("B: {0}", t1.B);
            Console.WriteLine("MethodWithoutArguments: {0}", t1.MethodWithoutArguments());
            Console.WriteLine("MethodWithArguments: {0}", t1.MethodWithArguments(5));

            p.Reflection(t1);
        }
        private void Reflection<T>(T item)
        {
            Type t = item.GetType();
            object classInstance = Activator.CreateInstance(t, null);
            Console.WriteLine("\nReflection");
            foreach (PropertyInfo propertyInfo in t.GetProperties())
            {
                object value = propertyInfo.GetValue(item, null);

                Console.WriteLine("{0} = {1}", propertyInfo.Name, value);
            }

            var temp = t.GetMethod("MethodWithoutArguments").Invoke(classInstance, null);
            Console.WriteLine("MethodWithoutArguments: {0}", temp);

            temp = t.GetMethod("MethodWithArguments").Invoke(classInstance, new object[] { 5 });
            Console.WriteLine("MethodWithArguments: {0}", temp);
        }
    }

    public class Test{
        public int A { get; set; }
        public string B { get; set; }
        public string MethodWithoutArguments()
        {
            return A + " " + B;
        }

        public string MethodWithArguments(int i)
        {
            return A + " " + i;
        }
    }
}

Output

  1. Normal

    • A: 2
    • B: test
    • MethodWithoutArguments: 2 test
    • MethodWithArguments: 2 5
  2. Reflection

    • A = 2
    • B = test
    • MethodWithoutArguments: 0 // incorrect
    • MethodWithArguments: 0 5 // incorrect

With the reflaction method I get correctly the Parametries but if I call a method, the result is wrong, what am I doing wrong?





Aucun commentaire:

Enregistrer un commentaire