C#.net 学习点滴
这里是在工作学习过程中碰到认为值得记录下的东西,本人水平有限。仅供自己使用。
1重载运算符
语法: public static ResultObject operator +(-|*|/|==)(ObjectClass c1,ObjectClass c2);
说明
ResultObject
返回的对象。可以同ObjectClass的,也可以是Boolean的类型。
+(-|*|/|==|!=)
需要重载的符号,包括加、减、乘、除、==、!=
ObjectClass
当前类的
下面是具体的代码
class Program
{
static void Main(string[] args)
{
Complex c1 = 5;
c1.show();
Complex c2 = c1 * 5;
c2.show();
Complex c3 = c1 + c2;
c3.show();
if (c3 != c1)
System.Console.WriteLine("yes");
else
System.Console.WriteLine("no");
}
}
class Complex
{
double x, y;
public Complex(double x, double y)
{
this.x = x; this.y = y;
}
public static implicit operator Complex(double x)
{
return (new Complex(x, 1.0));
}
public static Complex operator +(Complex c1, Complex c2)
{
return (new Complex(c1.x + c2.x, c1.y + c2.y));
}
public static Complex operator *(Complex c, double t)
{
return (new Complex(c.x * t, c.y * t));
}
public void show()
{
System.Console.WriteLine("HashCode={0}, x={1}, y={2}", this.GetHashCode(), x, y);
}
public static bool operator ==(Complex c1, Complex c2)
{
return ((c1.x == c2.x) && (c1.y == c2.y));
}
public static bool operator !=(Complex c1, Complex c2)
{
return ((c1.x != c2.x) || (c1.y != c2.y));
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
浙公网安备 33010602011771号