在项目中经常要引用到别人的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();
最新评论