【发布时间】:2014-12-30 04:23:39
【问题描述】:
大家下午好, 我试图通过传递适当的参数来动态调用函数。 假设函数如下所示:
公共字符串 CreatePerson(Person p)
对象 p 以 Json 形式接收,我想根据参数类型将其反序列化为适当的运行时类型,以便我可以将其传递给 Newtonsoft.Json 库函数 JsonConvert.DeserializeObject (jsonReceived)。
下面是我的代码:
m = this.GetType().GetMethod(method);
List<object> a = new List<object>();
foreach (var param in m.GetParameters())
{
//have to convert args parameter to appropriate function input
a.Add(ProcessProperty(param.Name, param.ParameterType, args));
}
object invokeResult = null;
invokeResult = m.Invoke(this, a.ToArray());
private object ProcessProperty(string propertyName, Type propertyType, string jsonStringObject)
{
if (propertyType.IsClass && !propertyType.Equals(typeof(String)))
{
var argumentObject = Activator.CreateInstance(propertyType);
argumentObject = JsonConvert.DeserializeObject<propertyType>(jsonStringObject);
return argumentObject;
}
}
我收到以下错误:
The type or namespace name 'propertyType' could not be found (are you missing a using directive or an assembly reference?)
我在哪里接近这个错误? 如何在运行时动态获取参数 Type,以便它可以处理 Person 以外的类型并能够将其传递给 DeserializeObject?
【问题讨论】:
-
误读了您的评论 dbc
标签: c# json json.net system.reflection