zoukankan      html  css  js  c++  java
  • 静态方法和实例方法对于委托的区别

    当一个类的实例的方法被赋给一个委托对象时,在上下文中不仅要维护这个方法,还要维护这个方法所在的实例。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,所以将静态方法赋值给委托时性能更优。

  • 相关阅读:
    上学路线 (Standard IO)
    舞台设置 (Standard IO)
    Circle (Standard IO)
    Number (Standard IO)
    Gift (Standard IO)
    圆周舞蹈 (Standard IO)
    竞赛排名 (Standard IO)
    奶牛排队 (Standard IO)
    奶牛晒衣服 (Standard IO)
    神奇的风 (Standard IO)
  • 原文地址:https://www.cnblogs.com/createwell/p/12708148.html
Copyright © 2011-2022 走看看