dev*_*xer 9 .net c# struct operator-overloading operators
假设我有一个只有一个字段的结构:
public struct Angle
{
public static readonly double RadiansPerDegree = Math.PI / 180;
private readonly double _degrees;
public Angle(double degrees)
{
_degrees = degrees;
}
public double Degrees
{
get { return _degrees; }
}
public double Radians
{
get { return _degrees * RadiansPerDegree; }
}
public static Angle FromDegrees(double value)
{
return new Angle(value);
}
public static Angle FromRadians(double value)
{
return new Angle(value / RadiansPerDegree);
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用,直到我想做这样的事情:
var alpha = Angle.FromDegrees(90);
var beta = Angle.FromDegrees(100);
var inequality = alpha > beta;
var sum = alpha + beta;
var negation = -alpha;
//etc.
Run Code Online (Sandbox Code Playgroud)
所以,我实现IEquatable<in T>和IComparable<in T>,但仍然没有启用任何运营商(甚至没有==,<,>=,等).
所以,我开始提供运算符重载.
例如:
public static Angle operator +(Angle a, Angle b)
{
return new Angle(a._degrees + b._degrees);
}
public static Angle operator -(Angle a)
{
return new Angle(-a._degrees);
}
public static bool operator >(Angle a, Angle b)
{
return a._degrees > b._degrees;
}
Run Code Online (Sandbox Code Playgroud)
然而,当我查看所有我可以想象的重载(+, -, !, ~, ++, --, true, false, +, -, *, /, %, &, |, ^, <<, >>, ==, !=, <, >, <=, >=)时,我开始觉得必须有更好的方法.毕竟,struct只包含一个字段,该字段是值类型.
有没有办法double一次性启用所有操作员?或者我真的必须输出我可能想要手动支持的每个操作员吗?
(即使我有两个或三个字段,我仍然希望能够在一个批处理中添加运算符...)
Mat*_*cey 12
重载操作符的重点是定义如何使用这些操作符添加操作自定义类型的对象,因此如果您的第二个字段是字符串数组,您希望如何自动实现++运算符?没有明智的答案,特别是因为我们不知道对象的上下文或它的用法,所以答案是肯定的,你必须自己重载操作符.
对于记录,如果你真的只需要一个字段,并且它只是一个双,那么首先不要使用结构,除非你需要重载操作符来执行一些其他操作,而不是默认情况下 - 它是一个明确过度工程的情况!