C# constructor event

后端 未结 6 824
南旧
南旧 2021-01-21 03:53

i created a class and when i create an employee object via form , i want to give a message;

this is my class, event and delegate

public delegate void cto         


        
6条回答
  •  感动是毒
    2021-01-21 04:26

    Solution

    Here's a generic approach to your problem

    public class EventFactory
    {
        public U Create(V constructorArgs)
        {
            var instance = (U)Activator.CreateInstance(typeof(U), constructorArgs);
            OnCreated?.Invoke();
            return instance;
        }
    
        public delegate void CreatedEventHandler();
        public event CreatedEventHandler OnCreated;
    }
    

    You can then do

    var ef = new EventFactory();
    ef.OnCreated += myEventHandler; 
    var instance = ef.Create(employeeArgs);
    

    .. Going further

    It is possible to adjust my code to provide greater flexiblity when you need to pass event arguments or when the constructor is parameterless. I haven't tested it but it should look somewhere along the lines of

    public class EventFactory
    {
        public U Create(V constructorArgs, T eventArgs)
        {
            var instance = (U)Activator.CreateInstance(typeof(U), constructorArgs);
            OnCreated?.Invoke(eventArgs);
            return instance;
        }
    
        public U Create(T eventArgs)
        {
            return Create(null, eventArgs);
        }
    
        public delegate void CreatedEventHandler(T args);
        public event CreatedEventHandler OnCreated;
    }
    
    public class EventFactory
    {
        public U Create(V constructorArgs)
        {
            var instance = (U)Activator.CreateInstance(typeof(U), constructorArgs);
            OnCreated?.Invoke();
            return instance;
        }
    
        public U Create() where U : new()
        {
            var instance = new U();
            OnCreated?.Invoke();
            return instance;
        }
    
        public delegate void CreatedEventHandler();
        public event CreatedEventHandler OnCreated;
    }
    

提交回复
热议问题