I want to make a generic EventArgs sub class that has a write-only property which, when updated by the code that is handling the event, will also update the byref parameter of the constructor of the class.
The code I have so far doesn't work. How do I get the property "Item" to update the "item" constructor parameter so I can retrieve the value that was set?
public class EventArgsSet<T> : EventArgs
{
public EventArgsSet(ref T item)
{
Item = item;
}
public T Item
{
private get;
set;
}
}
I want to be able to raise the event like this (VB.NET):
Dim myItem As SomeType = Nothing
Dim e = new EventArgsSet(Of开发者_开发问答 SomeType)(myItem)
RaiseEvent SomeEvent(Me, e)
//'Do something with myItem
And the event handler could look something like this:
Public Sub myObj_SomeEvent(sender As Object, e As EventArgsSet(Of SomeType)) Handles myObj.SomeEvent
e.Item = theObjectToSet
End Sub
Why do this via events? I think an event is the wrong idiom for what you're trying to do. Instead I would expose a callback method as a property, something like this:
Public Property GetMyItem As Func(Of SomeType) = Function() Return Nothing
Then you can simply do something like (my VB.Net syntax is a bit rusty on this):
Dim myItem = GetMyItem()()
And instead of registering an event, you would simply set the callback method like so:
myObj.GetMyItem() = Function() return theObjectToSet
Why wouldn't the class with the event handler have a field for this value you want to update? It seems to me like you are making the EventArgs class do too much.
Also, the way you have this doesn't work the way you want. (but I guess you see that isn't you are asking the question). It doesn't work because when you set the Item property, you are changing what the EventArgs class is pointing to.
精彩评论