[英]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.