SoFunction
Updated on 2025-04-10

Resolve how to use reflection to call type members methods, fields, properties


    class Program
    {
        static void Main(string[] args)
        {
            Type t = typeof(Test);
            object result;
            Test tc =new Test();
            ("Invoke a static method");
            ("Sayhello", | | , null, null, new object[] { });
            ("------------------------");
            ("Invoke a generic method");
            List<string> list = new List<string>();
            ("GuoHu");
            ("LeiHu");
            //We should assign the parameter type to generic method By using MakeGenericMethod
            MethodInfo mi = ("Print").MakeGenericMethod(typeof(string));
            (null, new object[] { list });
            ("------------------------");
            ("Invoke a instance method");
            MethodInfo m = ("Swap");
            object[] obj = new object[2];
            obj[0] = 123;
            obj[1] = 230;
            (new Test(), obj);
            ("{0},{1}", obj[0], obj[1]);
            ("------------------------");
            ("output field name");
            FieldInfo[] fi = ();
            foreach (FieldInfo name in fi)
            {
                ("{0}",name);
            }
            ("------------------------");
            ("Invoke a method with named parameters");
            object[] argValues = new object[] { "Guo", "Hu" };
            String[] argNames = new String[] { "lastName", "firstName" };
            ("PrintName", , null, null, argValues, null, null, argNames);
            ("------------------------");
            ("Get a field value");
            result = ("Name", | , null, tc, new object[] { });
            ("Name == {0}", result);
            ("------------------------");
            ("Set a field value");
            ("Name", , null, tc, new object[] { "New value" });
            result = ("Name", | , null, tc, new object[] { });
            ("Name == {0}",result);
        }
    }
    class Test
    {
        public string Name;
        public Test()
        {
            Name = "Initilize Name";
        }
        public static void Sayhello()
        {
            ("Sayhello");
        }
        public static void Print<T>(IEnumerable<T> item)
        {
            foreach (T t in item)
            {
                ("{0}", t);
            }
        }
        public static void PrintName(String firstName, String lastName)
        {
            ("{0},{1}", lastName, firstName);
        }
        public void Swap(ref int a, ref int b)
        {
            int x = a;
            a = b;
            b = x;
        }
    }