gpt4 book ai didi

c# - 如何使用 GetMethod 获取输入参数类型?

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:42 24 4
gpt4 key购买 nike

大家下午好我试图通过传递适当的参数来动态调用函数。假设函数如下所示:

public string 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?)

我在哪里接近这个错误?我如何在运行时动态获取参数类型,以便它可以处理 Person 以外的类型并将其传递给 DeserializeObject?

最佳答案

问题是泛型是在编译时完成的,而你只知道运行时的类型。本质上,编译器认为 propertyType 应该是编译后的类型,而不是 Type 类型的变量。

幸运的是,有重载可以让你做你想做的事,比如 DeserializeObject(String, Type)

像这样使用:

argumentObject = JsonConvert.DeserializeObject(jsonStringObject, propertyType);

关于c# - 如何使用 GetMethod 获取输入参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27695416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com