[英]Invoke method on class' base field with Reflection
我是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()
方法?
您可以通过反射方式从类中调用特定方法(请注意,该方法不应与需要在类的构造函数中初始化的值相关,因为该方法不会实例化该类):
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.