What I'm actually trying to achieve is:
I already have a property to my field.
Some other class in the application has a delegate/event (which I'm writing).
I need to register some function to this delegate to set my filed, but my
filed already has a the SET function inside the property of his. And I want
to avoid writing another Set method just for this event.
How can I do that?
------
Thanks
Sharon
Marc Gravell - 15 Nov 2006 12:55 GMT
Then I would use the 2.0 inline delegate syntax, but using the standard
event pattern. Depending on the scenario, the new value could be either in
the event-args, or back on the sender (typical for a SomethingChanged
event), i.e.
// EventHandler example
someInstance.SomethingChanged += delegate {
someOtherInstancePossiblyThis.SomeProperty = someInstance.Something;
};
or
// SomeEventHandler example where SomeEventArgs has a .SomeValue property
someInstance.SomeEvent += delegate (object sender, SomeEventArgs args) {
someOtherInstancePossiblyThis.SomeProperty = args.SomeValue;
};
(note that in either case you might also case "sender" instead of using
someOtherInstancePossiblyThis)
Marc
Jon Skeet [C# MVP] - 15 Nov 2006 19:10 GMT
> What I'm actually trying to achieve is:
>
[quoted text clipped - 7 lines]
>
> How can I do that?
You can use reflection to set it up. A complete example is below. It's
pretty longwinded, but if you needed this on a regular basis you could
easily set it up in a helper method - especially with generics, if
you're using 2.0.
using System;
using System.Reflection;
delegate void SettingHandler (string value);
class PropertyClass
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
class EventClass
{
public event SettingHandler SetEvent;
public void RaiseEvent (string value)
{
SetEvent(value);
}
}
class Test
{
static void Main()
{
PropertyClass pc = new PropertyClass();
EventClass ec = new EventClass();
PropertyInfo prop = typeof(PropertyClass).GetProperty("Name");
MethodInfo method = prop.GetSetMethod();
SettingHandler handler = (SettingHandler)
Delegate.CreateDelegate
(typeof(SettingHandler), pc, method);
ec.SetEvent += handler;
ec.RaiseEvent ("testing");
Console.WriteLine (pc.Name);
}
}

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too