C#中,下列操作符可以重载:
+ - ! ~ ++ 00 true false
* / % & | ^ << >> == != > < >= <=
下列操作符是不允许进行重载的:
= && || ?: new typeof sizeof is
// 操作符重载演示
using System;
class Player
{
public int neili;
public int tili;
public int jingyan;
public int neili_r;
public int tili_r;
public Player()
{
neili = 10;
tili = 50;
jingyan = 0;
neili_r = 50;
tili_r = 50;
}
// 一元操作符重载
public static Player operator ++(Player p)
{
p.neili = p.neili + 50;
p.tili = p.tili + 50;
p.neili_r = p.neili;
p.tili_r = p.tili;
return p;
}
// 二元操作符重载
public static Player operator +(Player p1, Player p2)
{
Player p = new Player();
p.neili = p1.neili +p2.neili;
p.tili = p1.tili + p2.tili;
p.neili_r = p.neili;
p.tili_r = p.tili;
return p;
}
public static void Main()
{
Player p1 = new Player();
Player p2 = new Player();
p1++;
Console.WriteLine(" {0}", p1.neili);
Player p = p1 + p2;
Console.WriteLine(" {0}", p.neili);
}
}