Link to home
Start Free TrialLog in
Avatar of bemara57
bemara57

asked on

How to invoke a static method by string name?

I've been having trouble overloading a delegate (I don't think it's possible), so my next step is to try reflection. I am trying to pass in a method as an argument to another method like this

MyClass someInstance = new MyClass();
MembershipUserCollection users = new MembershipUserCollection();
users = someInstance.ReturnUsers(someData, "ObjectWrapper.Users");

Then in my classes:
public class MyClass
{
    ...
    public MembershipUserCollection ReturnUsers(ListDictionary data, string objectMethod)
    {
          ...get stuff from db
          return objectMethod(cmd.ExecuteReader());  <=== Here's where I want to invoke objectMethod as ObjectWrapper.Users
    }
}

public static class ObjectWrapper
{
    public static MembershipUserCollection Users(IDataReader results)
    {
        MembershipUserCollection users = new MembershipUserCollection();

        while (results.Read())
           ...
    }

    // This is why delegate won't work for me, because I will not always pass IDataReader
    // Need to overload this method
    public static MembershipUserCollection Users(ListDictionary results)
    {
        MembershipUserCollection users = new MembershipUserCollection();

         foreach (DictionaryEntry .. in results)
           ...
    }
}

So how do I achieve this in the return line of MyClass.ReturnUsers?
Avatar of ZachSmith
ZachSmith
Flag of United States of America image

Use InvokeMember and in your BindingFlags include BindingFlags.Static
ASKER CERTIFIED SOLUTION
Avatar of ZachSmith
ZachSmith
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial