扩展方法

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。 对于用 C#、F# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法没有明显区别。
扩展方法可以理解为现有的类型(现有类型可以为自定义的类型和.Net 类库中的类型)扩展(添加)应该附加到该类型中的方法
它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 扩展方法当然不能破坏面向对象封装的概念,所以只能是访问所扩展类的public成员。

using System;
using Microsoft.VisualBasic;
using static System.Console;
namespace newIterator1
{
    class Program
    {
        static void Main(string[] args)
        {

            Student student=new Student(100,50);
            student.Learning();
            WriteLine(student.GetAvg());
            string str = "hello";
            str.SayHello();
            ReadKey();
        }
    }

    public class Student
    {
        public double width, height;
        public Student(double width, double height)
        {
            this.width = width;
            this.height = height;
        }

        public double Sum()
        {
            return width + height;
        }
    }

    public static class StudentExten
    {
        public static void Learning(this Student student)
        {
            WriteLine("Student is Learing");
        }

        public static double GetAvg(this Student student)
        {
            return student.Sum() / 2;
        }
    }


    // 必须是一个静态类
    public static class StringExten
    {
        //必须为public static 类型,且参数使用this关键字
        public static void SayHello(this  string str)
        {
            WriteLine("扩展方法"+str);
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值