Hi,
I'm a little unsure how to word the title to this question but I'm looking for a the shortest/aseist way in VB.NET (or C# but using VB.NET at the moment) to get the string value of a method's name dynamically given the method call.
For instance, I have a class like this:
Public Class Blah
Public Sub Foo()
End Sub
End Class
Now Foo is a strongly-typed cover for a dynamic setting and I have an event handler that will fire when the setting changes and return the string name of the setting that changed.
I'd like to be able to switch/select on this string and have a case based on the Foo() method. To do this I need to able to get the string name of the Foo method from the method call itself (i.e. somehow GetMethodName(blahInstance.Foo())).
-
I don't have VB.NET handy at the moment, but in C#, I'm thinking this is the answer. Does this look approximately like what you're looking for? If so, the VB.NET syntax should be relatively simple to work out:
Blah blahInstance = new Blah(); System.Action fooFunc = blahInstance.Foo; Console.WriteLine(fooFunc.Method.Name);John Saunders : I've been using .NET since before beta 1, and I don't believe I've ever seen System.Delegate.Method used. Thanks for my "something new" for today.John Saunders : OTOH, switching on the method name sounds like a _really_ bad idea, so maybe you should have kept the answer to yourself. ;-)Graphain : Well it seems better than switching on a string setting name because it is then strongly typed no?Graphain : Hmm, your example is great for my example but as I'm stuck with .NET 2.0 at the moment I don't think I have access to Func so I can't deal with methods that have a return type this way (Action is for no return types). Any ideas on if I'm missing anything?Graphain : @John Saunders I guess you are right - the proper way would probably be a new class type for each setting field but that seems like overkill.kvb : You can create your own Func or Action delegates; there's nothing special about them. For example "public delegate U Func(T t);". Graphain : Oh right, thanks. For some reason I was imagining I'd have to make a seperate delegate type for each method.
0 comments:
Post a Comment