关键字 operator
一定是一个公共的静态方法
返回值写在operator前
逻辑处理 是自定义的
基本语法
public static 返回类型 operator 运算符(参数列表) //参数多少由运算符决定
{
}
作用让自定义类和结构体对象可以进行运算
注意
条件运算符需要成对实现
一个符号可以多个重载
不能用ref out
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text.Json.Serialization;
struct Vector2
{
public int x;
public int y;
public Vector2(int x,int y)
{
this.x = x;
this.y = y;
}
public static bool operator ==( Vector2 a , Vector2 b)
{
if (a.y == b.y && a.x == b.x)
{ return true; }
else { return false; }
}
public static bool operator !=( Vector2 a , Vector2 b )
{
if (a.y == b.y && a.x == b.x)
{ return false; }
else { return true; }
}
}
class Vector3
{
public int x;
public int y;
public int z;
public Vector3() { }
public Vector3(int x,int y,int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static Vector3 operator +(Vector3 a,Vector3 b)
{
Vector3 v = new Vector3();
v.y = a.y + b.y;
v.x = a.x + b.x;
v.z = a.z + b.z;
return v;
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
Vector3 v = new Vector3();
v.y=a.y - b.y;
v.x=a.x - b.x;
v.z=a.z - b.z;
return v;
}
public static Vector3 operator *(Vector3 a, int b)
{
a.x *= b;
a.y *= b;
a.z *= b;
return a;
}
}
class Program
{
static void Main()
{
Vector2 vector = new Vector2(1,2);
Vector2 vector2 = new Vector2(1,3);
if (vector == vector2)
{
Console.WriteLine("对比成功相等");
}
else { Console.WriteLine("对比成功不相等"); }
Vector3 vector3 = new Vector3(1,2,3);
Vector3 vector31 = new Vector3(1,2,3);
int x = 5;
Vector3 receiver;
receiver = vector3+vector31;
Console.WriteLine(receiver.x+","+receiver.y+","+receiver.z);
receiver = vector3- vector31;
Console.WriteLine(receiver.x + "," + receiver.y + "," + receiver.z);
receiver = vector3 * 3;
Console.WriteLine(receiver.x + "," + receiver.y + "," + receiver.z);
}
}