概念 :为现有非静态 变量类型 添加 方法 如果类中的方法和拓展方法名称和参数都一样
作用 使用的时候会调用类中原本的方法。拓展方法
提升程序拓展性 不需要再在对象中重写方法 不会被调用
不需要继承来添加方法
为别人封装的类型写额外的方法
特点
一定是写在静态类中
一定是个静态函数
第一个参数用this 修饰
第一个参数为拓展目标
语法.
访问修饰符 static 返回值 函数名(this 拓展类名 参数名,参数类型 参数名2....)
{
}
static class C
{
public static void SpeakValue(this int value )
{
Console.WriteLine("为int拓展的方法"+value);
}
}
......
main
{
int i =10;
i.SpeakValue();
// 拓展类名是int ,value就是10
//运行打印“为int拓展的方法10”
}
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text.Json.Serialization;
static class C
{
public static int Square(this int value)
{
return value * value;
}
public static void Suicide(this Player p)
{
Console.WriteLine(p.Name + "自杀了");
}
}
class Player
{
public string Name
{
get;
set;
}
public float BloodVolume
{
get;
set;
}
public float Aggressivity
{
get;
set;
}
public float Def
{
get; set;
}
public void Attack()
{
Console.WriteLine(Name + "攻击");
}
public void Move()
{
Console.WriteLine(Name+"移动");
}
public void Injured()
{
Console.WriteLine(Name + "受伤了");
}
}
class Program
{
static void Main()
{
Player p = new Player();
p.Name = "Cer";
p.Attack();
p.Move();
p.Injured();
p.Suicide();
}
}