C#反射实体类

来源:互联网 发布:血手幽灵数据共享平台 编辑:程序博客网 时间:2024/05/16 10:57
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Reflection;
  5. namespace EasySRCoreClass.Component.UtilComponent
  6. {
  7.     public class ObjectMethod
  8.     {
  9.         private Type mytype;
  10.         private Object obj;
  11.         public ObjectMethod(Object obj)
  12.         {
  13.             this.obj = obj;
  14.             mytype = obj.GetType();
  15.         }
  16.         //设置属性值
  17.         public void SetPropertyValue(string name, Object value)
  18.         {
  19.             PropertyInfo[] pis = mytype.GetProperties();
  20.             for (int i = 0; i < pis.Length; i++)
  21.             {
  22.                 PropertyInfo pi = pis[i];
  23.                 if (pi.Name.Equals(name))
  24.                 {
  25.                     pi.SetValue(obj, value, null);
  26.                     break;
  27.                 }
  28.             }
  29.         }
  30.         //取属性值
  31.         public Object GetPropertyValue(string name)
  32.         {
  33.             Object result = null;
  34.             PropertyInfo[] pis = mytype.GetProperties();
  35.             for (int i = 0; i < pis.Length; i++)
  36.             {
  37.                 PropertyInfo pi = pis[i];
  38.                 if (pi.Name.Equals(name))
  39.                 {
  40.                     result = pi.GetValue(obj, null);
  41.                     break;
  42.                 }
  43.             }
  44.             return result;
  45.         }
  46.         public Object InvokeMethod(String method)
  47.         {
  48.             return InvokeMethod(method, null);
  49.         }
  50.         //调用方法
  51.         public Object InvokeMethod(String method, Object[] paras)
  52.         {
  53.             Object result = null;
  54.             MethodInfo[] mis = mytype.GetMethods();
  55.             for (int i = 0; i < mis.Length; i++)
  56.             {
  57.                 MethodInfo mi = mis[i];
  58.                 if (mi.Name.Equals(method))
  59.                 {
  60.                     result = mi.Invoke(obj, paras);
  61.                     break;
  62.                 }
  63.             }
  64.             return result;
  65.         }
  66.     }
  67. }
原创粉丝点击