美文网首页
C#扩展方法实现

C#扩展方法实现

作者: 清远_03d9 | 来源:发表于2019-08-25 00:48 被阅读0次

    扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 扩展方法当然不能破坏面向对象封装的概念,所以只能是访问所扩展类的public成员。
    扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

    1. 首先我们声明一个Student类,它包含了两个方法StuInfo,getStuInfo

    public class Student
    {
        public string StuInfo()
        {
            return "学生基本信息";
        }
        public string getStuInfo(string stuName, string stuNum)
        {
            return string.Format("学生信息:\n" + "姓名:{0} \n" + "学号:{1}", stuName, stuNum);
        }
    }
    

    2. 添加扩展方法,必须是静态类才可以

    public static class ExtensionStudentInfo
    {
    //声明扩展方法
    //要扩展的方法必须是静态的方法,Add有三个参数
    //this 必须有,string表示我要扩展的类型,stringName表示对象名
    //三个参数this和扩展的类型必不可少,对象名可以自己随意取如果需要传递参数,再增加一个变量即可
    public static string ExtensionStuInfo(this Student stuName)
    {
        return stuName.StuInfo();
    }
    

    3. 使用扩展方法

    static void Main(string[] args)
    {
    Student newstudent = new Student();
    //要使用对象调用我们的扩展方法
    string stuinfo = newstudent.ExtensionStuInfo();
    Console.WriteLine(stuinfo);
    Console.ReadKey();
    }
    

    相关文章

      网友评论

          本文标题:C#扩展方法实现

          本文链接:https://www.haomeiwen.com/subject/lcicectx.html