我有一堆从单个类继承的类。我正在使用反射来访问类,因为将要访问的类将在运行时更改。
但是在尝试调用超类声明的方法时遇到了一些麻烦。
这是我的父类:
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始终为null,当我尝试调用它时会导致此错误:
System.NullReferenceException: Object reference not set to an instance of an object
我还没有找到这个。
基本上,我只需要使用子项作为动态对象来调用super方法。我怎样才能做到这一点?
@Edit
@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.
答案 0 :(得分:0)
你可以这样做:
namespace StackOverFlowTest
{
using System;
class BaseClass
{
public int BaseClassMethod(int x)
{
return x * x;
}
}
class DerivedClass : BaseClass
{
}
class Program
{
static void Main()
{
var derivedType = typeof(DerivedClass);
var baseType = typeof(BaseClass);
var method = baseType.GetMethod("BaseClassMethod");
var derivedInstance = Activator.CreateInstance(derivedType);
var result = method.Invoke(derivedInstance, new object[] { 42 });
Console.WriteLine(result);
Console.ReadLine();
}
}
}