Reputation: 4659
The problem I am having is that I would like to call a method from a string. Here is what I am doing:
Building My List of Strings (Methods) there are three different checkboxList objects in my UI
private List<string> MyTest = new List<string>();
private void AddSelectedMethods()
{
foreach(XName item in BaseTestList.CheckedItems)
{
MyTests.Add(item.ToString());
}
foreach (XName item in AdminTestList.CheckedItems)
{
MyTests.Add(item.ToString());
}
foreach (XName item in SubscriberTestList.CheckedItems)
{
MyTests.Add(item.ToString());
}
}
Here is the Caller. If I take out the Reflections call and reference the method directly everything works but I don't want to get into crating a huge list of if else statements.
private void StartSiteTest(object sender, DoWorkEventArgs e)
{
if (!BackWorker1.CancellationPending)
{
if (SiteToTest == "estatesales.vintagesoftware.local" || SiteToTest == "localhost")
{
es = new EstateSaleTests(site, Sites.First(i => i.SiteUrl == SiteToTest), BasePath, SiteToTest, UseCurrentCompanies);
foreach (string test in MyTests)
{
// <<<!!!!!!!! ------ The next line returns null ------ !!!!!!!>>>
MethodInfo thisMethod = es.GetType().GetMethod(test);
thisMethod.Invoke(es, null);
}
}
}
}
Any help on what I am doing wrong would be greatly appreciated.
!!!----- EDIT -----!!!
I'm an idiot. I had the class set to the list of strings but I forgot to rename my Methods Sorry about that. Yes the Methods were public and they are accessible I just have to rename them to the correct names now.
Upvotes: 1
Views: 653
Reputation: 57159
I notice this has already been well-answered, but the following might still be of use.
Sometimes it is hard to find the method using reflection. You're currently just searching for public instance methods only. What I usually do when finding the method through reflection appears rather hard, is using GetMethods()
with different binding flags and check by hand whether the expected methods are there.
Note that when you specify binding flags, you must also specify BindingFlags.InvokeMethod | BindingFlags.Instance
. In addition, consider the following:
BindingFlags.Static
BindingFlags.IgnoreCase
BindingFlags.NonPublic
BindingFlags.FlattenHierarchy
GetMembers
instead.You can combine all flags with |
to search for everything. With a little bit trial and error you'll eventually find the set of binding params that you need.
Upvotes: 0
Reputation: 62256
The call you use seems pretty acceptable, imo.
The thing is that GetType().GetMethod()
is able to recover only public
methods.
See this MSDN link.
In order to access methods with different acessors use this GetMethod(string, BindingFlags) overload.
Hope this helps.
Upvotes: 3