关于扩展方法的小例子

ET框架的Component和System的配合大量使用了扩展方法,扩展方法可以在类B定义类A的方法,使A可以直接调用。

using System;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Student newstudent = new Student();

            string stuinfo = newstudent.StuInfo();
            Console.WriteLine(stuinfo);

            string stuinformation = newstudent.ExtensionGetStuInfo("quzijing", "20081766");
            Console.WriteLine(stuinformation);
        }
    }

    public class Student
    {
        public string StuInfo()
        {
            return "学生基本信息\n";
        }

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

    public static class ExtensionStudentInfo
    {
        //扩展方法必须是static类型,使用this关键字声明扩展方法,this表示要扩展的对象
        public static string ExtensionGetStuInfo(this Student student, string stuname, string stunum)
        {
            return student.getStuInfo(stuname, stunum);
        }
    }
}
posted @ 2021-11-18 21:34  qianxun0975  阅读(168)  评论(0编辑  收藏  举报