重载运算符的基本语法
在C#中,重载运算符需要通过operator关键字定义静态方法,方法名即为要重载的运算符符号。例如,重载+运算符的语法如下:
public static ReturnType operator +(Type1 a, Type2 b)
{
// 实现逻辑
}
支持重载的运算符类型
C#允许重载以下两类运算符:
- 一元运算符:如
+、-、!、~、++、--、true、false。 - 二元运算符:如
+、-、*、/、%、&、|、^、<<、>>、==、!=、<、>、<=、>=。
重载一元运算符的示例
以下代码展示了如何重载+和-一元运算符:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public static Point operator +(Point p)
{
return p; // 一元+通常直接返回原对象
}
public static Point operator -(Point p)
{
return new Point { X = -p.X, Y = -p.Y };
}
}
重载二元运算符的示例
以下代码展示了如何重载+二元运算符:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public static Point operator +(Point a, Point b)
{
return new Point { X = a.X + b.X, Y = a.Y + b.Y };
}
}
重载比较运算符的注意事项
重载比较运算符(如==和!=)时,必须成对重载,且逻辑需一致。通常还需要重写Equals和GetHashCode方法:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public static bool operator ==(Point a, Point b)
{
return a.X == b.X && a.Y == b.Y;
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj is Point p)
return this == p;
return false;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
}
不支持重载的运算符
以下运算符不能重载:
- 条件运算符(如
&&、||),但可通过重载&和|间接实现。 - 赋值运算符(如
=、+=),但重载+会自动支持+=。 - 索引运算符(如
[]),但可通过索引器实现类似功能。 - 类型转换运算符(如
(int)),但可通过定义显式/隐式转换实现。
隐式与显式类型转换的重载
可以通过implicit和explicit关键字重载类型转换:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public static implicit operator string(Point p)
{
return $"({p.X}, {p.Y})";
}
public static explicit operator Point(string s)
{
var parts = s.Split(',');
return new Point { X = int.Parse(parts[0]), Y = int.Parse(parts[1]) };
}
}
655

被折叠的 条评论
为什么被折叠?



