简体   繁体   中英

Invoke method on class' base field with Reflection

I'm completely new to Reflection and have been having some trouble with the following problem. Given the following class structure, I'd like to invoke AddAdornments() .

internal interface IVsCodeWindowManager
{
    int AddAdornments();
}    

internal class CompoundTextViewWindow
{
    private IVsCodeWindowManager _codeWindowManager;
}

internal class VsCodeWindowAdapter : CompoundTextViewWindow
{
}

I have an instance of VsCodeWindowAdapter:

VsCodeWindowAdapter projCodeWindow;

I'd like to invoke AddAdornments . For example, if everything was public the invocation would be :

projCodeWindow._codeWindowManager.AddAdornments();

I can get access to the _codeWindowManager FieldInfo with Reflection:

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

The following code returns null, I believe I need an instance of the base class to get access to the _codeWindowManager field.

var _codeWindowManager = _codeWindowManagerFieldInfo.GetValue(projCodeWindow);

How can I use Reflection to get access to the instance of the base class so I may invoke the AddAdornments() method?

You can invoke a specific method from a class using reflection this way (keep in mind the method should not be related to the values that need to be initialized in the constructor of the class, because this approach does not instantiate the class):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM