Add event handler during object initialization

后端 未结 2 555
半阙折子戏
半阙折子戏 2021-01-21 23:39

I need to pass a instance (which will be created in this very moment) of a certain type to a method. This type offers several events which I\'d like to subscribe to too, so my c

相关标签:
2条回答
  • 2021-01-22 00:29

    This is not possible right now but according to Roslyn it is planned and might be available in the future.

    --------------------------------------------------------------------------
    | Feature            | Example                                |   C#     |
    -------------------------------------------------------------------------|
    | Event initializers |  new Customer { Notify += MyHandler }; | Planned  |
    -------------------------------------------------------------------------|
    
    0 讨论(0)
  • 2021-01-22 00:32

    I can advise you next trick in case if source code available: add public property with type of you event that take incoming value on set and attach this handler to event you need

    For example:

    namespace TrickAddEventHandlerInObjectInitializer
    {
    class A
    {
        public EventHandler AddHandlerToEventByAssignMe
        {
            set { Event += value; }
        }
    
        public event EventHandler Event;
    
        public void DoSmthAndInvoke()
        {
            Event?.Invoke(this, new EventArgs());
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var a = new A
            {
                AddHandlerToEventByAssignMe = A_Event
            };
    
            a.DoSmthAndInvoke();
        }
    
        private static void A_Event(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题