PS:本系列笔记将会记录我此次在北京学习Unity开发的总体过程,方便后期写总结,笔记为日更。
笔记内容均为 自己理解,不保证每个都对。
C#笔记未按照难度排列
运算符重载
重载后的运算符能够实现原运算符不能实现的功能
运算符包括(+ - * /) (> < >= <= == !=) (& | ! ^)
注意事项 >< >= <= == !=必须成对出现
重载格式为:
访问权限 static 返回类型 operator 运算符(参数)
例如:重载+号
///
/// 重载运算符 +号 让Vector4能够加上一个数字
/// operator + 表示对运算符+号的重载
/// static是必须的,表示全局
/// Vector4表示返回类型
///
/// 等号左边Vector4
/// 右边的数字
///
public static Vector4 operator +(Vector4 leftValue, int tmpInt) //重载 +号,让Vector4类能够直接加上数字
{
leftValue.x += tmpInt;
leftValue.y += tmpInt;
leftValue.z += tmpInt;
leftValue.w += tmpInt;
return leftValue;
}
public static Vector4 operator +(Vector4 leftValue, Vector4 rightValue) //重载 +号,让Vector4类能够直接加上Vector4类修饰的变量
{
leftValue.x += rightValue.x;
leftValue.y += rightValue.y;
leftValue.z += rightValue.z;
leftValue.w += rightValue.w;
return leftValue;
}
测试代码为:
Vector4 vectorA = new Vector4(1); //(1, 1, 1, 1)
Vector4 vectorB = new Vector4(1); //(1, 1, 1, 1)
Vector4 vectorC = new Vector4(-3); //(-3, -3, -3, -3)
vectorA = vectorA + 1; //(1 + 1, 1 + 1, 1 + 1, 1 + 1) 即(2, 2, 2, 2)
vectorA.Debug();
vectorA = vectorA + vectorB; //(2 + 1, 2 + 1, 2 + 1, 2 + 1)即(3, 3, 3, 3)
vectorA.Debug(); //输出结果为3 3 3 3
vectorC.Debug(); //输出结果为-3 -3 -3 -3
其他运算符同理
注意:重载 > < >= <= == !=的时候运算符要成对出现
例如重载 ==:
public static bool operator ==(Vector4 leftValue, int tmpInt)
{
bool flag = false;
if (leftValue.x == tmpInt && leftValue.y == tmpInt && leftValue.z == tmpInt && leftValue.w == tmpInt) //只要x y z w有一项不等于tmpInt即为false
flag = true;
return flag;
}
public static bool operator !=(Vector4 leftValue, int tmpInt)
{
bool flag = false;
if (leftValue.x != tmpInt && leftValue.y != tmpInt && leftValue.z != tmpInt && leftValue.w != tmpInt) //只要x y z w有一项等于tmpInt即为false
flag = true;
return flag;
}
测试代码为:
if (vectorA == 3)
{
Console.WriteLine("vectorA == 3");
}
else
{
Console.WriteLine("vectorA != 3");
}
输出结果为:
重载布尔变量:
public static bool operator true(Vector4 leftValue)
{
return leftValue.x > 0;
}
public static bool operator false(Vector4 leftValue)
{
return leftValue.x <= 0;
}
测试代码为:
if (vectorA)
{
Console.WriteLine("vectorA.x > 0");
}
else
{
Console.WriteLine("vectorA <= 3");
}
输出结果为: