【问题标题】:Invoke method on class' base field with Reflection使用反射在类的基字段上调用方法
【发布时间】:2014-06-29 02:09:59
【问题描述】:

我对 Reflection 完全陌生,并且在以下问题上遇到了一些麻烦。鉴于以下类结构,我想调用AddAdornments()

internal interface IVsCodeWindowManager
{
    int AddAdornments();
}    

internal class CompoundTextViewWindow
{
    private IVsCodeWindowManager _codeWindowManager;
}

internal class VsCodeWindowAdapter : CompoundTextViewWindow
{
}

我有一个 VsCodeWindowAdapter 的实例:

VsCodeWindowAdapter projCodeWindow;

我想调用AddAdornments。例如,如果所有内容都是公开的,则调用将是:

projCodeWindow._codeWindowManager.AddAdornments();

我可以通过反射访问 _codeWindowManager FieldInfo:

var _codeWindowManagerFieldInfo = projCodeWindow.GetType().BaseType.GetField("_codeWindowManager", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);

以下代码返回null,我相信我需要一个基类的实例才能访问_codeWindowManager字段。

var _codeWindowManager = _codeWindowManagerFieldInfo.GetValue(projCodeWindow);

如何使用反射来访问基类的实例,以便调用AddAdornments() 方法?

【问题讨论】:

  • 您需要执行GetMethod() 以从codeWindowManager 的非空实例中获取MethodInfo,一旦您拥有该MethodInfo,您就可以调用它。

标签: c# reflection field instance base-class


【解决方案1】:

您可以通过这种方式使用反射从类中调用特定方法(请记住,该方法不应与需要在类的构造函数中初始化的值相关,因为这种方法不会实例化类) :

var InvokeMethod = typeof(YourClass).GetMethod("MethodName");
// or Get.Methods() 

InvokeMethod.Invoke(Arguements);
// if you use Get.Methods() you will get a collection of methods, enumerate in the collection to find what you want.

【讨论】:

  • YourClass 可以是其他人程序集中的内部类型吗?或者YourClass 是那种类型的实例?
  • @JoshVarty:只要包含在程序中,何乐而不为!但我不认为它可以是某事的一个实例。
  • @JoshVarty:那么你必须使用Activator来创建该类的实例,例如:dynamic x = Activator.CreateInstance<SomeType>();
猜你喜欢
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多