【问题标题】:casting error while dynamically invoking a function that returns a custom type动态调用返回自定义类型的函数时出现强制转换错误
【发布时间】:2016-11-01 19:31:48
【问题描述】:

我在命名空间 tool1 中有一个名为 customType 的类。

我正在使用其他一些方法(命名空间 tool1 中的 class1),名为routine1 - 返回一个“自定义类型列表”,如下所示。

此代码返回一个没有错误的自定义类型列表:

    List<tool1.class1.customType> result1 = new List<tool1.class1.customType>();
    result1 = tool1.class1.routine1(argsAsStr, p_values);

以下代码也可以正常运行,没有错误,并返回一个对象,如下:

    Assembly tool1 = Assembly.LoadFrom(@"C:\tool1\tool1\bin\Debug\tool1.dll");
    Type type = tool1.GetType("tool1.class1");
    object instance = Activator.CreateInstance(type);
    object[] parametersArray = new object[] { argsAsStr, p_values};
    MethodInfo method = type.GetMethod("routine1");
    object result2 = method.Invoke(instance, parametersArray); 

但是,当我尝试将结果转换为 List 而不是对象时,我收到了转换错误:

    Assembly tool1 = Assembly.LoadFrom(@"C:\tool1\tool1\bin\Debug\tool1.dll");
    Type type = tool1.GetType("tool1.class1");
    object instance = Activator.CreateInstance(type);
    object[] parametersArray = new object[] { argsAsStr, p_values};
    MethodInfo method = type.GetMethod("routine1");
    List<tool1.class1.customType> result2 = method.Invoke(instance, parametersArray)

错误信息:

Error: Cannot implicitly convert type 'object' to 'System.Collections.Generic.List<tool1.class1.customType>'. 
An explicit conversion exists (are you missing a cast?) 

如何克服这个转换错误,并希望在调用方法后返回“不是”对象而是“customType 列表”??

提前感谢您的关注和贡献,

艾库特

【问题讨论】:

  • 例如,“在 tool1.class1 下”是什么意思?如果您提供minimal reproducible example,会更容易为您提供帮助。 (我也强烈建议您开始遵循 .NET 命名约定。)
  • 感谢 Jon Skeet 的提示。我会这样做并相应地编辑问题。

标签: c# reflection types


【解决方案1】:

您忘记转换method.Invoke 的结果(返回object):

var result2 = (List<tool1.class1.customType>)method.Invoke(instance, parametersArray);

【讨论】:

  • 感谢您的帮助。根据您的建议,我尝试了此铸造,但没有成功。我会深入挖掘并为您提供详细的错误消息。再次感谢您的帮助。
【解决方案2】:

您的“方法”返回的是您的自定义类型的单个实例,而不是该类型的列表。

试试:

List<tool1.class1.customType> result2 = new List<tool1.class1.customType>();
result2.Add(method.Invoke(instance, parametersArray));

【讨论】:

  • 问题是MethodInfo.Invoke 返回object。需要将结果转换为他想要的类型。
猜你喜欢
  • 1970-01-01
  • 2018-04-24
  • 2010-11-11
  • 2014-04-28
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多