Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

拓展方法

一、定义

为现有的 非静态类变量类型 添加新方法

二、作用

  1. 提升程序拓展性
  2. 不需要在对象中重新写方法
  3. 不需要继承来添加方法
  4. 为别人封装的类型写额外的方法

三、特点

  1. 一定是写在静态类中
  2. 一定是个静态函数
  3. 第一个参数为拓展目标
  4. 第一个参数用 this 修饰

四、基本语法

1
2
3
4
访问修饰符 static 返回值 函数名(this 变量类型 变量名,函数参数类型 函数参数名,函数参数类型 函数参数名···)
{

}

五、实例

1
2
3
4
5
6
7
8
9
10
11
12
static class Tools
{
public static void SpeakValue(this int value)
{
Console.WriteLine("为int拓展的方法"+ value);
}
static void Main(string[] args)
{
int i = 0;
i.SpeakValue();
}
}

注意事项

如果拓展方法和现有的非静态类中,函数有出现重复的情况 则拓展方法无效

评论