Hey,
I have a large number of methods and I need to call one of them, based on some integer. Of course I could just use a Select Case statement like so
(except like 5 times longer)Code:Select Case someInteger Case 0 Me.Method1() Case 1 Me.SomeOtherMethod() Case 2 Me.Method45() Case 3 Me.FinalMethod() End Select
But I'd rather not do that. I thought perhaps I could create a dictionary instead, where the keys are the integers, and the values are the methods.
The problem is, I'm not sure how I should do this. I am certain it has to do with delegates, but I'm not very familiar with them...
I've tried to declare the dictionary like so:
I then wasn't sure how to add a value to it... I thought I needed to use the AddressOf operator, but that doesn't seem to work:Code:Private _MethodDictionary As New Dictionary(Of Integer, [Delegate])
It underlines the AddressOf part saying:Code:_MethodDictionary.Add(0, AddressOf OnDownButtonClicked)
Right... So why does it work in an AddHandler statement? I think all the AddressOf operator did was create a delegate that points to the method provided?'AddressOf' expression cannot be converted to 'System.Delegate' because type 'System.Delegate' is declared 'MustInherit' and cannot be created.
So I then tried something else, using the Action class:
VS accepts this, ok great!Code:_MethodDictionary.Add(0, New Action(AddressOf OnDownButtonClicked))
But now I need to invoke this method, and I'm not sure how to do that... I could only find 'DynamicInvoke', or I could access the Method property (as a MethodInfo object) and call its Invoke method, passing in the object ("Me"). But that doesn't seem like a very good approach, I want to avoid Reflection as much as possible...
I'm starting to think I'm going about this the wrong way, so I decided to just ask it here. I'm sure a few of you know exactly how to do this.
Another few quite important things to note are:
1. The thread title says VS2008, but I am actually coding in VS2010. However, I need to downgrade this project back to VS2008 when I'm done with it, so I cannot use any VS2010-only features. Whatever I use must be compatible with VS2008 when I downgrade it later.
2. That also means, no .NET framework 4.0 stuff. In fact, I would like to keep it 2.0 if that's possible at all.
Thanks!




Reply With Quote