我對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字段信息與反思:
var _codeWindowManagerFieldInfo = projCodeWindow.GetType().BaseType.GetField("_codeWindowManager", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
下面的代碼返回null,我相信我需要的實例基類訪問_codeWindowManager
字段。
var _codeWindowManager = _codeWindowManagerFieldInfo.GetValue(projCodeWindow);
如何使用反射來獲取訪問基類的實例,所以我可以調用AddAdornments()
方法?
你需要做一個[GetMethod()](http://msdn.microsoft.com/en-us/library/system.type.getmethod%28v=vs.110%29.aspx )從'codeWindowManager'的非空實例中獲取一個'MethodInfo',一旦你有了這個MethodInfo你就可以調用它。 – slugster