我有一堆继承自单个类的类。我使用反射来访问类,因为将被访问的类将在运行时更改。
但是当我试图调用在超类中声明的方法时,我遇到了一些麻烦。
这是我的父类:
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]);
methodinfo总是null,当我试图调用它们时,会导致这个错误:
System.NullReferenceException: Object reference not set to an instance of an object
我还没有找到这个。
基本上,我只需要调用使用子对象作为动态对象的超方法。我怎样才能做到这一点呢?@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.
你可以这样做:
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();
}
}
}