zoukankan      html  css  js  c++  java
  • C# 扩展方法

          虽然自己以前用过扩展方法,但是从来没有认真总结过什么是扩展方法,前天面试被问到什么是扩展方法,在什么情况下使用,没答出来,现在在网上找了一下,做个小结,希望能看到此文的朋友给出指正。

          在项目中经常要引用到别人的dll,假设dll中有个student类, 该类中只有GetName()方法,如果需要GetAge()方法,有不能修改Dll源码,该怎么办呢?此时有两个办法,一是继承student类,二是扩展student中的方法,这里我们来介绍扩展方法,首先来建一个cs文件,实现student类:

      public class student

    {

      public student(){}

      public string name { get; set; }

      public int age {set;get;}

      public student(string name,int age)

      {

         this.age = age;

         this.name = name;

      }

    }

    编译后这个文件将形成Dll,我们在Aspx的后台页面实现一下代码:

    static class exStudent //这里必须是静态类

    {

     public static int GetAge(this student st) {return st.age};

     }

    这样就成功扩展了student类的方法;可如下使用GetAge()方法

    student st = new student("AA",12);

    st.GetAge();

     

  • 相关阅读:
    c# 遮罩
    判断当前task中的运行的activity是否为当前应用
    Chrome+SwitchySharp+myentunnel+SSH
    vps
    系统制作
    vs2010 mfc
    android ndk
    乐 Phone刷机教程(全过程)
    mysql 保留字 冲突
    mysql 存储过程
  • 原文地址:https://www.cnblogs.com/liuxvpiaopiao/p/2105386.html
Copyright © 2011-2022 走看看