0

I have a bunch of classes that inherit from a single class. I'm using reflections to access the classes, since the ones that will be accessed will change in runtime.

But I am having some trouble when trying to invoke a method declared at superclass.

Here is my parent class:

public class ParentClass {

    public ParentClass (Type type) {

    }

    public string method0String () {
        return string;
    }

    public void method1Void (string) {

    }

}

Here is my child class:

public class ChildClass : ParentClass {

    public ParentClass () : base(typeof(ChildClass)) {

    }

}

Here is the abstract class code where I cast the methods:

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]);

The MethodInfos are always null, which causes this error when I try to invoke them:

System.NullReferenceException: Object reference not set to an instance of an object

I haven't found anyway around this.

Basically, I just need to invoke a super method using the child as the dynamic object. How can I achieve this?

@Edit

After @nvoigt answer, my code looks like this:

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]);

And the error is a little different:

System.Reflection.TargetException: Object does not match target type.

1 Answers1

0

You can do it this way:

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();
    }
  }
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142