为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 };
        }
    }
posted @   张占岭  阅读(421)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示