Json.Net JToken调用 AspectCore.Extensions.Reflection 抛出异常
htrlq opened this issue · 1 comments
htrlq commented
class Program
{
static void Main(string[] args)
{
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(new { age = 10, name = "Hello" });
var dynamic = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(jsonString);
var type = dynamic.GetType();
var method = typeof(AService).GetMethod("Return");
method.MethodToArgs(dynamic);
}
}
public static class MethodInfoExtension
{
private static Lazy<MethodInfo> ValueMethod = new Lazy<MethodInfo>(() =>
{
var method = typeof(Extensions).GetMethod("Value", new[] { typeof(IEnumerable<JToken>) });
return method;
});
public static Dictionary<string, object> MethodToArgs(this MethodInfo method, JObject jObj)
{
var args = new Dictionary<string, object>();
var @params = method.GetParameters();
for (var index = 0; index < @params.Length; index++)
{
var param = @params[index];
var item = jObj[param.Name];
var _method = ValueMethod.Value;
var currentMethod = _method.MakeGenericMethod(param.ParameterType);
var arg = currentMethod.GetReflector().Invoke(item, null);
args[param.Name] = arg;
}
return args;
}
}
public class AService
{
public int Return(int age, string name)
{
return age + name.Length;
}
}
运行抛出异常
System.NullReferenceException:“Object reference not set to an instance of an object.”
htrlq commented
fix code
\\var arg = currentMethod.GetReflector().Invoke(item, null);
var arg = currentMethod.GetReflector().Invoke(item, new[] { item });