【发布时间】:2015-10-06 03:13:12
【问题描述】:
我有一堆类继承自一个类。我正在使用反射来访问这些类,因为将要访问的类会在运行时发生变化。
但我在尝试调用在超类中声明的方法时遇到了一些麻烦。
这是我的父类:
public class ParentClass {
public ParentClass (Type type) {
}
public string method0String () {
return string;
}
public void method1Void (string) {
}
}
这是我的孩子班:
public class ChildClass : ParentClass {
public ParentClass () : base(typeof(ChildClass)) {
}
}
这是我在其中转换方法的抽象类代码:
Type childType = Type.GetType(className[i]);
ConstructorInfo childConstructor = childType.GetConstructor(new Type[0]);
object childObject = null;
childObject = childConstructor.Invoke(childObject, new object[0]);
MethodInfo parentMethod0String = childType.GetMethod("method0String");
MethodInfo parentMethod1Void = childType.GetMethod("method1Void");
parentMethod1Void.Invoke(childObject, new object[]{argString});
object finalString = parentMethod0String.Invoke(childObject, new object[0]);
MethodInfos 始终为空,当我尝试调用它们时会导致此错误:
System.NullReferenceException: Object reference not set to an instance of an object
我还没有找到这个。
基本上,我只需要使用子对象作为动态对象调用一个超级方法。我怎样才能做到这一点?
@编辑
@nvoigt 回答后,我的代码如下所示:
Type childType = Type.GetType(className[i]);
object childObject = Activator.CreateInstance(childType);
Type parentType = Type.GetType("ParentClass");
MethodInfo parentMethod0String = parentType.GetMethod("method0String");
MethodInfo parentMethod1Void = parentType.GetMethod("method1Void");
parentMethod1Void.Invoke(childObject, new object[]{argString});
object finalString = parentMethod0String.Invoke(childObject, new object[0]);
而且错误有点不同:
System.Reflection.TargetException: Object does not match target type.
【问题讨论】:
-
您遇到了什么问题?错误信息?
-
我正在编辑以添加更多信息。 :D
-
GetConstructor 接受一个带有构造函数参数的数组,而不是目标对象实例
-
@vc74 是的,我知道。但由于某种原因,在调用构造函数后它为空。我现在改为 Activator.CreateInstance( ) 以避免垃圾代码。
-
@eddie_cat 上面的链接,答案是使用 BindingFlags.FlattenHierarchy 对我不起作用。对不起。
标签: c# reflection .net-2.0 superclass