如何将变量类型转换为另一种变量类型

时间:2018-06-08 17:19:37

标签: c# reflection type-conversion

我有一个对象数组,所有对象数组都填充了特定的命令参数(类型string):

object[] args = {"@all", "1", "true"};

我有这个方法:

public void Method(string client, int num, bool type)<br/>

我想将对象数组中指定的参数传递给方法。如何将每个对象数组元素转换为方法所期望的特定类型?

注意:方法参数类型未修复,因此我需要将对象数组中的项目转换为编译时未知的不同类型。

第49行格式错误: https://pastebin.com/bQLsbs59

1 个答案:

答案 0 :(得分:1)

您可以使用MethodInfo获取方法的参数。然后使用ParameterInfo,您可以获得该参数的类型。然后最后一步是使用Convert将每个字符串的类型更改为正确的类型。

object[] args = { "@all", "1", "true" };

MethodInfo methodInfo = typeof(Form1).GetMethod("Method");
ParameterInfo[] paramInfos = methodInfo.GetParameters();

// Should check that args.Length == paramInfos.Length.

// The arguments converted to their correct types will go in here.
object[] convertedArgs = new object[args.Length];

for (int i = 0; i < args.Length; i++)
{
  // Should do a try/catch here in-case the string can't be
  // converted to the parameter type. i.e. trying to convert
  // "abc" to an int.

  // Change each string to the appropriate type.
  convertedArgs[i] = Convert.ChangeType(args[i],
    paramInfos[i].ParameterType);
}

// Finally, we can call the method with the arguments that have
// been converted to the correct types.
methodInfo.Invoke(this, convertedArgs);
相关问题