我有一个带有自定义属性的方法,该属性列出了同一类中可以调用的其他方法。我将被调用的方法传递给另一个类函数,它将读取属性并选择属性中命名的一个方法并返回它的委托。如果可能的话,我很难弄清楚如何用反射或事件来做到这一点。
<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
初始调用将进入JellyBean(),并且在被执行管理器选中后将调用JellyBeanBlack、JellyBeanRed、JellyBeanWhite、jellybeanggreen函数中的一个。
已更新以避免中间包装器委托
我的VB生锈了,所以我用c#:
var methodNames = similarAttr.ChildBehaviors;
var randomMethodStr = methodNames[new Random().Next(methodNames.Length)];
return (Action)Delegate.CreateDelegate(source.Target, randomMethodStr);
我应该指出这里有一种代码气味:您可能想要考虑为什么您试图以这种方式调用方法,并考虑是否可能有更好的设计实践来实现您想要的