是否可以在 C# 中创建一个表示度数的对象?

Is it possible to make an object which represents degrees in c#?

是否可以有一个 class 或包含一个 float 值的结构,该值只能在 0 到 359.999 之间...如果您将它增加到超过其最大值,它将重置为0 或递减超过 0 时低于 360 的正值。

实施后,它看起来像这样:

Degrees angle = 359;
angle += 2;
Console.WriteLine(angle);

输出:

1

或者递减到 0 以下时:

Degrees angle = 0;
angle -= 2;
Console.WriteLine(angle);

输出:

358

它还需要能够 increment/decrement 高于 360f 的值,因此将 361.5 添加到 0 将输出 1.5

你可以像这样创建结构

public struct Degrees
{
   private decimal _angle;

   public decimal angle
   {
       get { return _angle; }
       set { _angle = value % 360; }
   }
}

然后用作

Degrees degrees = new Degrees();
degrees.angle = 361.5m + 0m;

结合 operator overloading and implicit 个关键字,很容易做到:

public readonly struct Degrees
{
    private readonly float _value;

    public Degrees(float value)
    {
        _value = value < 0
            ? 360 - (Math.Abs(value) % 360)
            : value % 360;
    }

    public override string ToString() 
        => _value.ToString();

    public static implicit operator Degrees(float f) 
        => new Degrees(f);

    public static Degrees operator +(Degrees a, Degrees b) 
        => new Degrees(a._value + b._value);
    public static Degrees operator -(Degrees a, Degrees b) 
        => new Degrees(a._value - b._value);
}

现在你可以这样写了:

Degrees angle = 359f;
angle += 2f;
Console.WriteLine(angle);

将输出:

1

或者这样:

Degrees angle = 0;
angle -= 2;
Console.WriteLine(angle);