mardi 16 août 2016

Get name of a variable (from a non-static variable) and use it to access this variable via reflection

This question was a very tough one to find the right words for, so please don't blame me too much :).

Basically here is the situation:

1) I KNOW how to get the name of a variable;

2) I KNOW how to access a variable via reflection, knowing it's name.

What I want is to get the name (string) dynamicaly and immediately receive access to a non-static variable using the string I've just derrived WITHOUT making an empty class instance for that.

Confusing right? Well, here is the deal: we have a winforms project, when the project was started, we decided that we will not inherit our forms from our very own parent, that is all of our forms inherit the basic Microsoft's Form. Right now we have a situation, where we have some of the forms with a common functionality (say search) and some without. What we want is to be able to call the common methods on the currently active from from the other form IF THEY EXIST.

Simple to do, right?

Form currentlyActiveForm = GetCurrentlyActiveForm();  // imagine we have this method

dynamic currentForm = currentlyActiveForm;
try
{
currentForm.CommonMethod();
}
catch
{
}

Ugly? Maybe, but that is how it is in our project right now and it gets the job done. My problem with this? If I press Shift+F12 on any of the CommonMethod() definitions I see no references at all. Am I being picky? Maybe, but still I want to know the following code is possible in the All Mighty language:

Form currentlyActiveForm = GetCurrentlyActiveForm();
string commonMethodName = MyUtils.GetVariableName(() => MyChildForm.CommonMethod);
// mind, CommonMethod() is NON-static!
...
[proceed to access and call the method, using reflection]

So is the above code possible without getting a compiler error?





Aucun commentaire:

Enregistrer un commentaire