Ceres
Ceres

Reputation: 3648

How to find methods in the same class from a passed delegate

I have a method with a custom attribute that lists other methods in the same class that it can call. I'm passing the called method to another class function that will read the attribute and pick one of the methods named in the attribute and return it's delegate. I'm having a hard time figuring out how to do this with reflection or event if it is possible.

<AttributeUsage(AttributeTargets.Method, allowmultiple:=False)>
Public Class ExecuteSimiliar
    Inherits System.Attribute

    Public ReadOnly ChildBehaviors() As String

    Public Sub New(ParamArray childBehaviors() As String)

        Me.ChildBehaviors = childBehaviors

    End Sub

End Class

Public Class MyMethods

    <ExecuteSimiliar("JellyBeanBlack", "JellyBeanRed", "JellyBeanWhite", "JellyBeanGreen")>
    Public Shared Sub JellBean()

        Dim myFunction As Action = ExecuteManager.Choose(AddressOf JellBean)
        myFunction.Invoke()

    End Sub

    Public Shared Sub JellyBeanBlack()
        'Do something
    End Sub

    Public Shared Sub JellyBeanRed()
        'Do something
    End Sub

    Public Shared Sub JellyBeanWhite()
        'Do something
    End Sub

    Public Shared Sub JellyBeanGreen()
        'Do something
    End Sub

End Class

Public Class ExecuteManager

    Public Shared Function Choose(source As Action) As Action

        Dim similarAttr As ExecuteSimiliar
        similarAttr = CType(Attribute.GetCustomAttribute(source.Method, GetType(ExecuteSimiliar)), ExecuteSimiliar)

        'Select random function name from similarAttr
        'Get sibling methods from source delegate
        'Return selected method delegate. (JellyBeanBlack, JellyBeanRed, JellyBeanWhite, JellyBeanGreen)

    End Function

End Class

The inital call would be into JellyBean() and one of the JellyBeanBlack, JellyBeanRed, JellyBeanWhite, JellyBeanGreen functions would get invoked after being selected by the execution manager.

Upvotes: 1

Views: 80

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156524

Updated to avoid intermediate wrapper delegate

My VB is rusty, so I'm using C#:

var methodNames = similarAttr.ChildBehaviors;
var randomMethodStr = methodNames[new Random().Next(methodNames.Length)];
return (Action)Delegate.CreateDelegate(source.Target, randomMethodStr);

I should point out that there is a code smell here: you may want to consider why you are trying to call methods this way, and think if there might be a better design practice to achieve what you want.

Upvotes: 1

Related Questions