静态方法和实例方法对于委托的区别
程序员文章站
2023-08-25 14:40:25
当一个类的实例的方法被赋给一个委托对象时,在上下文中不仅要维护这个方法,还要维护这个方法所在的实例。System.Delegate 类的Target属性指向的就是这个实例。举个例子: class Program { static void Main(string[] args) { X x = ne ......
当一个类的实例的方法被赋给一个委托对象时,在上下文中不仅要维护这个方法,还要维护这个方法所在的实例。system.delegate 类的target属性指向的就是这个实例。举个例子:
class program { static void main(string[] args) { x x = new x(); progressreporter p = x.instanceprogress; p(1); console.writeline(p.target == x); // true console.writeline(p.method); // void instanceprogress(int32)
} static void writeprogresstoconsole(int percentcomplete) { console.writeline(percentcomplete+"%"); } static void writeprogresstofile(int percentcomplete) { system.io.file.appendalltext("progress.txt", percentcomplete + "%"); } } class x { public void instanceprogress(int percentcomplete) { // do something
} }
但对于静态方法,system.delegate 类的target属性是null,所以将静态方法赋值给委托时性能更优。