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; }             }
        }
}

转载于:https://www.cnblogs.com/nickli/archive/2011/04/02/2003660.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值