【问题标题】:How to use a superclass method using reflections C#如何使用反射 C# 使用超类方法
【发布时间】: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


【解决方案1】:

你可以这样做:

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();
    }
  }
}

【讨论】:

  • 是的,我可以这样做,但是有几个类,因为它们是从外部数据库自动生成的......我真的需要更自动化的东西。 ://
  • 您究竟需要什么自动化?您可以轻松地自动执行此操作。
  • 对不起,我看错了你的答案。我实际上尝试了您的解决方案,但问题是... System.Reflection.TargetException: Object does not match target type.
  • 那么您收到的是什么?您当前的代码是什么?
猜你喜欢
  • 2011-07-21
  • 1970-01-01
  • 2016-12-12
  • 2023-03-30
  • 1970-01-01
  • 2011-07-25
  • 2018-02-18
相关资源
最近更新 更多