zoukankan      html  css  js  c++  java
  • C#中的扩展类的理解

    扩展类是一种静态的一种类的调用方法,通过实例化进行调用。利用this进行指正该类,有参数的时候直接在后面追加参数。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    //必须定义为公共的静态类
    public static class Studentinfo{
        //定义一个添加学生姓名的扩展方法
        public static string AddStuname(this string stuname){
                   return studentname;
               }        
         //添加多个参数的扩展方法
        public static string AddStudentinfo(this string stuname,string stunum){
                  return string.Format("学生信息: "+"学生姓名:{0} "+"学生学号:{1}",stuname,stunum);
                }
    }
     
     
    //这种方法跟一般的调用方法一致
    //实例化类然后直接使用函数就行
    class  Students
    {
            public static void Main(string[] args){
                    studentinfo stu=new studentinfo();
                    string stuinfo=stu.Addstuname();
                    string stuinfos=stu.AddStudentinfo("sldkfj","001");
                    Console.WriteLine(stuinfo);
                    Console.WriteLine(stuinfos);
                 }
    }
     
    //为stu类扩展(一般用于不知道类中的源代码,只知道功能时候)
    pulic class Stu{
                 public void foo(){
                  ....
                }
                 public void fo(string stuname,string stuno){
                    ....
                 }
    }
     
    //stu类的扩展类
    public static class ExtenStu{
               //传参进行类的实例化
               public static string ExtenStuAdd(this Stu student){
                    return student.foo();
                  }
                //传参进行类的实例化,有参数在后面追加
                public static string ExtenStuAddinfo(this Stu students,string stusname,string stusnum)
                   {
                      return students.fo(stusname,stusnum);
                    }
     }
  • 相关阅读:
    LINQ篇:查询句法
    DLINQ(五):存储过程
    DLINQ(六):探究特性
    DLINQ
    LinQ 扩展函数的应用
    Linq 入门系列 select篇
    Linq 入门系列 [Take,Skip,TakeWhile,SkipWhile]篇
    javascript导航动画效果
    javascript简单的计算器实现
    javascript简单的日历实现
  • 原文地址:https://www.cnblogs.com/guanshan/p/guan2020-1-13_001.html
Copyright © 2011-2022 走看看