在用反射对方法进行调用时,需要对类的方法进行解析
#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