【发布时间】: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