Are EventArg classes needed now that we have generics

前端 未结 4 814
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 06:31

With generics, is there ever a reason to create specific derived EventArg classes

It seems like now you can simply use them on the fly with a generic implementation.

4条回答
  •  不思量自难忘°
    2020-12-29 06:57

    Look at the Custom Generic EventArgs article written by Matthew Cochran, in that article he describes how to expand it even further with two and three members.

    Using generic EventArgs have their uses, and of course their misuses, as type information is lost in the process.

    public class City {...}
    
    public delegate void FireNuclearMissile(object sender, EventArgs args);
    public event FireNuclearMissile FireNuclearMissileEvent;
    
    public delegate void QueryPopulation(object sender, EventArgs args);
    public event QueryPopulation QueryPopulationEvent;
    

    In the following example it is type-safe, but a bit more LOC:

    class City {...}
    
    public class FireNuclearMissileEventArgs : EventArgs
    {
        public FireNuclearMissileEventArgs(City city)
        {
            this.city = city;
        }
    
        private City city;
    
        public City City
        {
            get { return this.city; }
        }
    }
    
    public delegate void FireNuclearMissile(object sender, FireNuclearMissileEventArgs args);
    public event FireNuclearMissile FireNuclearMissileEvent;
    
    public class QueryPopulationEventArgs : EventArgs
    {
        public QueryPopulationEventArgs(City city)
        {
            this.city = city;
        }
    
        private City city;
    
        public City City
        {
            get { return this.city; }
        }
    }
    
    public delegate void QueryPopulation(object sender, QueryPopulationEventArgs args);
    public event QueryPopulation QueryPopulationEvent;
    

提交回复
热议问题