【问题标题】:How to get input parameter Type using GetMethod?如何使用 GetMethod 获取输入参数类型?
【发布时间】: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?

【问题讨论】:

标签: c# json json.net system.reflection


【解决方案1】:

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

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

这样使用:

argumentObject = JsonConvert.DeserializeObject(jsonStringObject, propertyType);

【讨论】:

  • 没问题。您会发现,通常沿着这些线的任何通用内容都有这样的重载。希望你现在对泛型有了更多的了解,这样你就能明白为什么会发生这个问题,并且知道如果你遇到类似的事情,你应该寻找替代方案(如其他重载)。 :)
【解决方案2】:

您不能使用运行时 System.Type propertyType 作为泛型方法的类型参数。而是使用采用运行时类型的DeserializeObject 的重载:

argumentObject = JsonConvert.DeserializeObject(jsonStringObject, propertyType);

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多