2014-06-29 60 views
0

我對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()方法?

+1

你需要做一個[GetMethod()](http://msdn.microsoft.com/en-us/library/system.type.getmethod%28v=vs.110%29.aspx )從'codeWindowManager'的非空實例中獲取一個'MethodInfo',一旦你有了這個MethodInfo你就可以調用它。 – slugster

回答

0

您可以通過這種方式使用反射來調用特定方法(請記住,該方法不應該與需要在類的構造函數中初始化的值相關,因爲此方法不會實例化類):

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. 
+0

'YourClass'可以是來自其他人的程序集的內部類型嗎?或者'YourClass'是該類型的一個實例? – JoshVarty

+0

@JoshVarty:只要它包含在程序中,爲什麼不呢!但我不認爲它可能是某種事物的一個實例。 – Transcendent

+0

@JoshVarty:然後你必須使用'Activator'來創建該類的一個實例,例如:'dynamic x = Activator.CreateInstance ();' – Transcendent