浅析反射调用(Reflection Call)

5 篇文章 0 订阅
1 篇文章 0 订阅

    在用反射对方法进行调用时,需要对类的方法进行解析

#region 了解方法分属性和调用
            Person person = new Person() { Name = "郭**", Age = 8 };
            Type t1 = typeof(Person);
            Type t2 = person.GetType();

            string strMsg = "";

            //获取事件
            EventInfo[] events = t2.GetEvents();
            foreach (EventInfo item in events)
            {
                strMsg += "</ b>" + item.Name;
            }
            //获取公共字段(Public Field)
            FieldInfo[] fields = t2.GetFields();
            foreach (FieldInfo item in fields)
            {
                strMsg += "</ b>" + item.Name;
            }
            //获取类的所有方法
            MethodInfo[] methods = t2.GetMethods();
            foreach (MethodInfo item in methods)
            {
                strMsg += "</ b>" + item.Name;
            }
            #endregion

通过上面的类转换我们可以看到类对应的属性和方法和事件等信息。

下面我们讲讲反射调用的原理也和这个差不多代码如下:

类库 Common:
namespace Common
{
    public class CommFun
    {
        #region 通过配置反射调用
        /// <summary>
        /// 通过配置反射调用
        /// </summary>
        /// <param name="iDb"></param>
        ///<param name="strReflectConfig">RealEstateConfig配置的函数名</param>
        ///<param name="arrObj">参数数组</param>
        public object ReflectionInvoke(string strReflectConfig, object[] arrObj)
        {
            //通过配置反射调用
            string strReflect = GetConfig(strReflectConfig);
            if (!string.IsNullOrEmpty(strReflect))
            {
                string[] arrReflect = strReflect.Split('@');
                if (arrReflect.Length == 3)
                {
                    //Type type = Assembly.LoadFile(HttpContext.Current.Server.MapPath(@"~/bin/" + arrReflect[0])).GetType(arrReflect[1], false);
                    string path = System.AppDomain.CurrentDomain.BaseDirectory + arrReflect[0];//+ @"~/bin/Debug/"
                    Type type = Assembly.LoadFile(path).GetType(arrReflect[1], false);
                    MethodInfo method = type.GetMethod(arrReflect[2]);
                    object obj = Activator.CreateInstance(type);
                    return method.Invoke(obj, arrObj);

                }
            }
            return null;
        }
        #endregion
        #region 取根目录AppConfig.config配置文件
        /// <summary>
        /// 取根目录AppConfig.config配置文件
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public string GetConfig(string strKey)
        {
            System.Collections.IDictionary dic = (System.Collections.IDictionary)System.Configuration.ConfigurationManager.GetSection("AppConfig");
            if (dic[strKey] == null)
            {
                return "";
            }
            return dic[strKey].ToString();
        }
        #endregion
        
    }
}
配置 App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <section name="AppConfig" type="System.Configuration.DictionarySectionHandler"></section>
</configSections>
<AppConfig configSource="AppConfig.config">
</AppConfig>
</configuration>

 

配置表 AppConfig.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<AppConfig>
  <!--反射调用-->
  <add key="ReflectionInvoke" value="Model.dll@Model.ReflectionCall@FunTwo" />
</AppConfig>
Main方法 
CommFun comFun = new CommFun();
object[] arrObj = new object[2];
arrObj[0] = "One";
arrObj[1] = "Two";
this.lblResult1.Text = comFun.ReflectionInvoke("ReflectionInvoke", arrObj).ToString();

结果:FunOne:One|Two

希望对你有帮助:

原理参考网址:

网址一:https://www.cnblogs.com/DrHao/p/5401006.html

网址二:https://www.cnblogs.com/xuwendong/p/7575181.html

如果配置AppConfig.config出现异常:

参考资源:配置异常处理

 

2.反射调用深入探究;

1.创建类实例,动态绑定赋值

#region 属性赋值
            PayInfo pay = new PayInfo();
            string payInfoValue = "1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16";
            string[] split = { "|" };
            string[] strs = payInfoValue.Split(split, StringSplitOptions.None);
            string[] fileds = { "PrimaryKey", "ConsNo", "ConsName", "OrgNo", "RcvOrgNo", "AcctOrgNo", "BankCode", "RcvAmt", "RcvedAmt", "RcvedPenalty", "PrepayAmt", "AcctBal", "PayDate", "TypeCode", "PayMode", "SettleMode" };
            for (int j = 0; j < strs.Length; j++)
            {
                try
                {
                    PropertyInfo propertyInfo = pay.GetType().GetProperty(fileds[j]);
                    if (propertyInfo != null )
                    {
                        propertyInfo.SetValue(pay, strs[j], null);
                    }

                    //pay.GetType().GetProperty(fileds[j]).SetValue(pay, strs[j], null);
                    if (pay != null && !string.IsNullOrEmpty(fileds[j]))
                    {
                        PropertyInfo _findedPropertyInfo = pay.GetType().GetProperty(fileds[j]);
                    }
                }
                catch (Exception ex)
                {
                    string exception =  ex.ToString();
                    Console.WriteLine(exception);
                }
            }

            #endregion

 2.属性赋值

public class PropertyHelper
    {
        /// <summary>
        /// 反射得到实体类的字段名称和值
        /// var dict = GetProperties(model);
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="t">实例化</param>
        /// <returns></returns>
        public static Dictionary<object, object> GetProperties<T>(T t)
        {
            var ret = new Dictionary<object, object>();
            if (t == null) { return null; }
            PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            if (properties.Length <= 0) { return null; }
            foreach (PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(t, null);
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    ret.Add(name, value);
                }
            }
            return ret;
        }

        /// <summary>
        /// 利用反射来判断对象是否包含某个属性
        /// </summary>
        /// <param name="instance">object</param>
        /// <param name="propertyName">需要判断的属性</param>
        /// <returns>是否包含</returns>
        public static bool ContainProperty(object instance, string propertyName)
        {
            if (instance != null && !string.IsNullOrEmpty(propertyName))
            {
                PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName);
                return (_findedPropertyInfo != null);
            }
            return false;
        }


        /// <summary>
        /// 获取对象属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="propertyname"></param>
        /// <returns></returns>
        public static string GetObjectPropertyValue<T>(T t, string propertyname)
        {
            Type type = typeof(T);
            PropertyInfo property = type.GetProperty(propertyname);
            if (property == null)
            {
                return string.Empty;
            }
            object o = property.GetValue(t, null);
            if (o == null)
            {
                return string.Empty;
            }
            return o.ToString();
        }

        /// <summary>
        /// 获取属性列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void GetObjectProperty<T>()
        {
            Type t = typeof(T);
            System.Reflection.PropertyInfo[] properties = t.GetProperties();
            foreach (System.Reflection.PropertyInfo info in properties)
            {
                Console.Write("name=" + info.Name + ";" + "type=" + info.PropertyType.Name + ";value=" + GetObjectPropertyValue<Object>(new object(), info.Name) + "<br />");
            }
        }


    }
            #region 获取类的所有属性
            Dictionary<object, object> dictList = PropertyHelper.GetProperties<PayInfo>(pay);
            System.Reflection.PropertyInfo[] member = pay.GetType().GetProperties();
            #endregion

Test方法: 动态绑定与解析;

#region para[]
            TestMethod3 testMethod3 = new TestMethod3();
            string s = "guoxiongfneg";
            TestMethod test = new TestMethod();
            List<int> iList = new List<int>() { 1,2,3,4,5,6};
            testMethod3.GetAllDicData(s,test,iList);
            string keyName = iList.GetType().Name.ToString();
            var iiList = (List<int>)testMethod3.StepDicData[keyName];
            int kkkk = iiList[0];

            #endregion
public class TestMethod: ITestMethod
    {
        public TestMethod()
        {

        }
        public virtual Dictionary<string, string> ItemAssemble(string m, string n)
        {
            return new Dictionary<string, string>();
        }

        
    }
    public class TestMethod2 : TestMethod
    {
        public TestMethod2()
        {

        }
        public override Dictionary<string, string> ItemAssemble(string m, string n)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>() { };
            dic.Add(m, n);
            return dic;
        }
    }

    public class TestMethod3
    {
        public Dictionary<string, object> StepDicData { get; set; }
        public TestMethod3()
        {
            StepDicData = new Dictionary<string, object>();
        }
        
        public void GetAllDicData(params object[] inputs)
        {
            for (int i = 0; i < inputs.Count(); i++)
            {
                StepDicData.Add(inputs[i].GetType().Name.ToString(), inputs[i]);
            }   
        }
    }
            #region 反射调用
            string strPath = System.AppDomain.CurrentDomain.BaseDirectory + @"bin\DAL.dll";
            var assembly =  Assembly.LoadFrom(strPath);
            var types = assembly.GetTypes();
            MethodInfo Method = assembly.GetTypes()[4].GetMethod("Add");
            
            object obj = Activator.CreateInstance(assembly.GetTypes()[4]);
            Object[] arrObj = { 3 ,1};
            object kk = Method.Invoke(obj, arrObj) ;

            var instance = assembly.CreateInstance(types[4].FullName);
            #endregion
            #region Virtual and override differ.
            Dictionary<string ,string> dic = testMethod.ItemAssemble( "a", "1");
            Dictionary<string, string> dic2 = testMethod2.ItemAssemble("a", "1");
            if (dic2.Any())
            {
                string dpOne = dic2.TryGetValue("a",out string outString).ToString();
            }
            
            #endregion

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fengzhilu000

送人玫瑰,手留余香!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值