NickLi

导航

C# 反射用法小结

在C#编程中反射还是蛮常用的,下面是一些简单用法的小结:

class Program
{
        static void Main(string[] args)         {
            Student st = new Student();
            object[] argss = { 2, 3 };

            // 通过反射调用方法
            object resultO = InvokeMethod<Student>("Sum", st, argss);
            Console.WriteLine(resultO);

            // 通过反射调用方法
            InvokeMethodSnippet();
            // 通过反射给属性赋值
            SetValueSnippet();

            Console.ReadKey();
        }

        // if invoke a static method, use null for obj.         // did not handle the override for parameters.
        static public object InvokeMethod<T>(string methodName, T obj, object[] args)         {
            System.Reflection.MethodInfo method = typeof(T).GetMethod(methodName);
            return method.Invoke(obj, args);         }
 
        // 
        static public void InvokeMethodSnippet()
        {
            object obj = new Student();
            string methodName = "Sum";
            Type t = obj.GetType();
            object[] args = { 2,3 };
            object result = t.InvokeMember(methodName, System.Reflection.BindingFlags.InvokeMethod |
                                System.Reflection.BindingFlags.Public |
                                System.Reflection.BindingFlags.Instance,                                 null,
                                obj,
                                args);
            Console.WriteLine(result);         }

        // create a new instance
        static public T CreateNewInstance<T>()
        {             T t = Activator.CreateInstance<T>();
            return t;
        }

        // get, set value for property         static public void SetValueSnippet()
        {
            Student st = new Student();             System.Reflection.PropertyInfo info = typeof(Student).GetProperty("Name");
            info.SetValue(st, "Nick", null);
            Console.WriteLine(st.Name);
            Console.WriteLine(info.GetValue(st, null));         }

        class Student
        {
            public int Sum(int a, int b)             {
                return a + b;
            }

            string _name;
            public string Name             {
                get { return _name; }
                set { _name = value; }             }
        }
}

posted on 2011-04-02 16:06  孤叶无眠  阅读(887)  评论(0编辑  收藏  举报