如何使用 GetMethod 获取输入参数类型

本文关键字:参数 类型 输入 获取 何使用 GetMethod | 更新日期: 2023-09-27 18:35:33

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

公共字符串 CreatePerson(Person p)

对象 p 作为 Json 接收,我想根据参数 Type 将其反序列化为适当的运行时类型,以便我可以将其传递到 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?

如何使用 GetMethod 获取输入参数类型

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

幸运的是,有一些重载可以让您做您想做的事,例如DeserializeObject(String, Type)

像这样使用:

argumentObject = JsonConvert.DeserializeObject(jsonStringObject, propertyType);

不能将运行时 System.Type propertyType 用作泛型方法的类型参数。相反,请使用采用运行时类型的DeserializeObject重载:

argumentObject = JsonConvert.DeserializeObject(jsonStringObject, propertyType);