zoukankan      html  css  js  c++  java
  • 为JS和C#类加一个扩展方法吧:P

    JS扩展方法:通过原型prototype为JS的function扩展一个新的function
    <script>
        function Rectangle(width, height) {
            this.width = width;
            this.height = height;
        }
        //为js的一个function添加一个方法,即我们通过原型prototype为一个class添加一个method
        Rectangle.prototype.adds = function (rec) {
            if (rec instanceof Rectangle) {
                return  (rec.width*rec.height);
            }
            else {
                alert("Invalid Rectangle object!");
            }
        }
        var v = new Rectangle(3, 2);
        v = v.adds(v); //使用扩展方法
        alert("面积是:"+v);
    </script>

    C#扩展方法:在不改类本身的前提下,为其扩展一个新的方法.

     public class Rectangle
        {
            public double Width
            {
                get;
                set;
            }
     
            public double Height
            {
                get;
                set;
            }
        }
     
     
        public static class Extension
        {
            public static Rectangle Adds(this Rectangle p, Rectangle p1)
            {
                return new Rectangle { Width = p.Width + p1.Width, Height = p.Height + p1.Height };
            }
        }
  • 相关阅读:
    重谈MST及Kruskal算法
    小技巧—边权转点权
    JDOJ 1062 过路费
    总结—二分答案求解问题
    CF10D LCIS
    NOIP 2012 摆花
    SDOI 2014 旅行
    CF550C Divisibility by Eight
    CF295C Greg and Friends
    USACO Closing the Farm
  • 原文地址:https://www.cnblogs.com/lori/p/2059063.html
Copyright © 2011-2022 走看看