文章目录
前言
我上篇文章已经基本解决了反射的基本问题,现在只留下了一乌云,就是Json化对象如何转化为MethodInfo 的参数入参
但是反射的问题还有一朵解决不了的乌云,Json字符串参数入参MethodInfo。
直接运行MethodInfo
我们直接写一个简单的函数
/// <summary>
///
/// </summary>
/// <param name="age"></param>
/// <param name="name"></param>
/// <param name="person"></param>
public void TestParamters(int age, string name, T_Person person)
{
Console.WriteLine(JsonConvert.SerializeObject(new {
age = age, name = name, person = person }));
}
static void Main(string[] args)
{
//从程序集中拿出
SwitchService switchService = new SwitchService();
var method = typeof(SwitchService).GetMethod("TestParamters");
if (method != null)
{
//默认方法
method.Invoke(switchService, new object[] {
15, "小天", new T_Person() });
}
Console.WriteLine("运行完成!");
Console.ReadKey();
}
运行结果
这个是非常好解决的,但是有个问题,我们运行反射的时候根本不知道如何入参的个数和类型。我们还需要解决Json到Paramters的问题
Json解决
ParamterInfo实例化
static void Main(string[] args)
{
//从程序集中拿出
SwitchService switchService = new SwitchService();
var method = typeof(SwitchService).GetMethod("TestParamters");
//需要反序列化的字符串
var paramterStr = @"{""age"":0,""name"":null,""person"":{""Name"":null,""Age"":0,""Sex"":null}}";
if (method != null)
{
//默认方法
method.Invoke(switchService, new object[] {
15, "小天", new T_Person() });
var parameterInfos = method.GetParameters();
object[] methodParams = new object[parameterInfos.Length];
for (int i = 0; i < parameterInfos.Length; i++)
{
var item = parameterInfos[i];
//通过程序集创建实例化对象
Type itemType = item.ParameterType;
try
{
//无法实例化无默认构造函数的方法
methodParams[i] = System.Activator.CreateInstance(itemType, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
method.Invoke(switchService, methodParams);
//method.Invoke(switchService, new object[] { paramterStr });
}
//var methods = MyAttributeHelper.GetAllMethods<MySwitchAttribute>(typeof(SwitchService));
Console.WriteLine("运行完成!");
Console.ReadKey();
}
运行结果
无法实例化问题部分参数的问题
简单来说,有些对象就是无法实例化的,默认只能为Null,
Json反序列化
但是我感觉我想的有点多了,我直接把Json对象拆分了不就行了。
但是Json反序列化有个问题,你必须要告诉他这个类是什么,他才能反序列化。就是我们要通过ParamterInfos给出反序列化的模型
因为Method.invoke必须参数的类型一致,而我默认直接转为Object类型,是有点问题的。
经过长达一天的研究,我终于完全的解决的了
安装Json序列化工具