1、运算符重载=。=,自己定义的类可能使用到的运算符的功能不同,比如+,-,*等在向量里就有着不同的意义。于是我们来看看一个简单的Vector2类
class Vector2
{
public int x { get; set; }
public int y { get; set; }
public Vector2() {
}
public Vector2(int x,int y) {
this.x = x;
this.y = y;
}
public static Vector2 operator +(Vector2 o1, Vector2 o2) //此处的public &static是必须的,去掉会错误
{
return new Vector2(o1.x + o2.x, o1 .y + o2.y);
}
public static Vector2 operator -(Vector2 o1, Vector2 o2)
{
return new Vector2(o1.x - o2.x, o1.y - o2.y); //必须返回,并使用new <类名>(。。。)
}
public override string ToString()//重写ToString方法来方便输出向量
{
return "("+x+","+y+")";
}
}
main中:
public static void Main()
{
Vector2 v1 = new Vector2(1, 2);
Vector2 v2 = new Vector2(3, 4);
Console.WriteLine((v1-v2).ToString ());
Console.ReadKey();
}
2、typeof(x) x必须是类名或类型,可以获取x的类型名称。
y.gettype() y是一个对象,获取对象的类名称。
<img src="https://img-blog.csdn.net/20160214154223726?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" width="34" height="34" alt="" />
这一章好快。下一章表达式与语句。174 _(:зゝ∠)_。