Sharon <Sh*****@newsgroups.nospamwrote:
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?
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);
}
}
--
Jon Skeet - <sk***@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