I am trying to create a delegate (as a test) for:
Public Overridable ReadOnly Property PropertyName() As String
My intuitive attempt was declaring the delegate like this:
Public Delegate Function Test() As String
And instantiating like this:
Dim t As Test = AddressOf e.PropertyName
But this throws the error:
Method 'Public Overridable ReadOnly Property PropertyName() As String' does not have a signature compatible with delegate 'Delegate Function Test() As String'.
So because I was dealing with a property I tried this:
Public Delegate Property Test() As String
But this throws a compiler error.
So the question is, how do I make a delegate for a property?
See this link:
Here is a C#/.NET 2.0 version of Marc Gravell's response:
Again, 'Delegate.CreateDelegate' is what is fundamental to this example.
This is good idea
But take care if your are doing something like this:
Calling this:
Will always return value of property of the last object in Collection
In this case you should call method:
Here's a C# example but all the types are the same:
First create the interface(delegate). Remember, a method that you attach to your delegate must return the same type, and take the same parameters as your delegate's declaration. Don't define your delegate in the same scope as your event.
Make an event based on the delegate:
Define a method that can be tied to your event that has an interface identical to the delegate.
Tie the method to the event. The method is called when the event is fired. You can tie as many methods to your event. I don't know the limit. It's probably something crazy.
What happens here is the method is added as a callback for your event. When the event is fired, your method(s) will be called.
Next we make a method that will fire the event when called:
Then you simply call the method -- JournalBase_Modified() -- somewhere in your code and all methods tied to your event are called too, one after another.
I just create an helper with pretty good performance : http://thibaud60.blogspot.com/2010/10/fast-property-accessor-without-dynamic.html It don't use IL / Emit approach and it is very fast !
Edit by oscilatingcretin 2015/10/23
The source contains some casing issues and peculiar
=""
that have to be removed. Before link rot sets in, I thought I'd post a cleaned-up version of the source for easy copy pasta, as well as an example of how to use it.Revised source
Use it like this:
VB version:
Re the problem using AddressOf - if you know the prop-name at compile time, you can (in C#, at least) use an anon-method / lambda:
I'm not a VB expert, but reflector claims this is the same as:
Does that work?
Original answer:
You create delegates for properties with
Delegate.CreateDelegate
; this can be open for any instance of the type, of fixed for a single instance - and can be for getter or setter; I'll give an example in C#...