public partial class FormTest : Form
{
public FormTest()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
string str = "Hello Extension Methods";
//调用扩展方法,必须用对象来调用
int len = str.TestMethod();
MessageBox.Show("长度为:" + len);
}
}
public static class Extensions
{
//要添加的扩展方法必须为一个静态方法
//此方法参数列表必须以this开始 第二个即为要扩展的数据类型,在这里就是要扩展string类型
//第三个就无所谓了,就是一对象名,名字随便,符合命名规则即可
//综合来讲,此方法就是要给string类型添加一个叫TestMethod的方法,此方法返回一个string型的值
public static int TestMethod(this string s)
{
return s.Length;
}
}
***********************************************************************************
public partial class FormTest : Form
{
public FormTest()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
Student stu = new Student();
//调用扩展方法,必须用对象来调用
MessageBox.Show(stu.TestMethod());
MessageBox.Show(stu.TestMethod("rete"));
}
}
public class Student
{
public string Description()
{
return "Student...";
}
public string Description(string name)
{
return "the student’s name is " + name;
}
}
public static class Extensions
{
//要添加的扩展方法必须为一个静态方法
//此方法参数列表必须以this开始 第二个即为要扩展的数据类型,在这里就是要扩展Student类型
//第三个就无所谓了,就是一对象名,名字随便,符合命名规则即可
//综合来讲,此方法就是要给Student类型添加一个叫TestMethod的方法,此方法返回一个string型的值
public static string TestMethod(this Student stu)
{
return stu.Description();
}
//要添加的扩展方法必须为一个静态方法
//此方法参数列表第一个参数表示要扩展哪一个类,第二个参数才表示此扩展方法的真正参数
//综合来讲,此方法就是要给Student类型添加一个叫TestMethod的方法, 此方法带有一个string类型的参数,并返回一个string型的值
public static string TestMethod(this Student stu, string name)
{
return stu.Description(name);
}
}
C#3.0扩展方法
最新推荐文章于 2025-08-09 22:19:42 发布