深入浅出.NET泛型编程(下)
这在上面的例中在成功的,但也存在特殊情形:有时我们确实想传递一个集合的派生类,此时需要一个集合的基类。例如,考虑一下Animal(如Monkey),它有一个把Basket<Fruit>作参数的方法Eat,如下所示:
现在,你可以调用:
public delegate void NotifyDelegate(Object info); public interface ISource { event NotifyDelegate NotifyActivity; }
如果我们各有一个上面每个类的对象,我们将为事件注册一个处理器,如下所示:public class StockPriceSource : ISource { public event NotifyDelegate NotifyActivity; //… } public class BoilerSource : ISource { public event NotifyDelegate NotifyActivity; //… }
StockPriceSource stockSource = new StockPriceSource(); stockSource.NotifyActivity += new NotifyDelegate(stockSource_NotifyActivity); //这里不必要出现在同一个程序中 BoilerSource boilerSource = new BoilerSource(); boilerSource.NotifyActivity += new NotifyDelegate(boilerSource_NotifyActivity); 在代理处理器方法中,我们要做下面一些事情: 对于股票事件处理器,我们有: void stockSource_NotifyActivity(object info) { double price = (double)info; //在使用前downcast需要的类型 } 温度事件的处理器看上去会是: void boilerSource_NotifyActivity(object info) { Temperature value = info as Temperature; //在使用前downcast需要的类型 }
public delegate void NotifyDelegate<t>(T info); public interface ISource<t> { event NotifyDelegate<t> NotifyActivity; }
而Boiler的源代码看上去象这样:public class StockPriceSource : ISource<double> { public event NotifyDelegate<double> NotifyActivity; //… }
如果我们各有一个上面每种类的对象,我们将象下面这样来为事件注册一处理器:public class BoilerSource : ISource<temperature> { public event NotifyDelegate<temperature> NotifyActivity; //… }
现在,股票价格的事件处理器会是:StockPriceSource stockSource = new StockPriceSource(); stockSource.NotifyActivity += new NotifyDelegate<double>(stockSource_NotifyActivity); //这里不必要出现在同一个程序中 BoilerSource boilerSource = new BoilerSource(); boilerSource.NotifyActivity += new NotifyDelegate<temperature>(boilerSource_NotifyActivity);
温度的事件处理器是:void stockSource_NotifyActivity(double info) { //… }
这里的代码没有作downcast并且使用的类型是很清楚的。void boilerSource_NotifyActivity(Temperature info) { //… }