Chase Florell
Chase Florell

Reputation: 47377

.net loop through methods in a class

I've got a Class with an undetermined number of methods inside

Public Class MyClass
    Public Sub Foo()
    End Sub

    Public Sub Bar()
    End Sub
End Class

Is there an easy way to call all of the methods in "MyClass" without physically specifying each one? The reason for this is that the methods within "MyClass" are going to be evergrowing, and I don't want to specify the method call for each one when the end goal is to execute every method on a set schedule.

IE: I want to avoid

Page_Load
    Foo()
    Bar()

Edit:

I've tried the following code to loop through the methods, but I'm getting an error

    Public Shared Sub Calculator()
        Dim methods As New Methods()
        For Each Info As MethodInfo In methods.GetType.GetMethods
            Info.Invoke(Nothing, Nothing)
        Next
    End Sub

System.Reflection.TargetException: Non-static method requires a target.

Upvotes: 0

Views: 283

Answers (3)

Sam Johnson
Sam Johnson

Reputation: 981

Here's a simple example, invoking methods without parameters:

Sub Main()
    Dim FooClass As New someClass()

    For Each method As MethodInfo In FooClass.GetType.GetMethods(BindingFlags.Instance Or
                                                                 BindingFlags.Public Or
                                                                 BindingFlags.DeclaredOnly)
        Console.WriteLine("Invoking: {0}.{1}()", method.DeclaringType.Name, method.Name)
        method.Invoke(FooClass, Nothing)
    Next
End Sub

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72658

You'll want Type.GetMethods to get a list of the methods, and then use MethodInfo.Invoke to call it.

Though it sounds to me like you're going about this the wrong way. Rather than using reflection to invoke every method on the class, I would suggest you look into delegates and events. That way, the class can register itself to get called instead of relying on heuristics to do the calling (for example, what would happen if you added a "helper" method to the MyClass class that you didn't want to get called?)

As an example, here's how you could use events to do this:

class MySchedule
{
    public event EventHandler Fire;

    public void Tick()
    {
        if (Fire != null) {
            Fire(this, EventArgs.Empty);
        }
    }
}

class MyClass
{
    public void Register(MySchedule sched)
    {
        sched.Fire += Foo;
        sched.Fire += Bar;
    }

    void Foo(object source, EventArgs e)
    {
    }

    void Bar(object source, EventArgs e)
    {
    }
}

I've used the built-in EventHandler delegate, but you can use whatever you like if you want the methods to have a specified signature.

Upvotes: 2

ryaner
ryaner

Reputation: 3997

http://msdn.microsoft.com/en-us/library/aa332480(v=VS.71).aspx

I think this is what you are looking for. .NET Reflection allows you to do this very easily.

Upvotes: 0

Related Questions