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();

     

  • 相关阅读:
    12月11日
    081212 晴
    12月10日
    树莓派项目——基于树莓派的WIFI网络互传系统设计
    IDE
    边缘检测
    Android Launcher桌面应用快捷方式的开发
    android ui事件处理分析
    listview 分析
    ApplicationsIntentReceiver.class
  • 原文地址:https://www.cnblogs.com/liuxvpiaopiao/p/2105386.html
Copyright © 2011-2022 走看看