【问题标题】:Help with implicit operator overload in C#帮助 C# 中的隐式运算符重载
【发布时间】:2011-05-13 05:39:53
【问题描述】:

我正在尝试创建一个名为 LoopingInt 的类。它存储两个整数,一个是整数的最大值,另一个是存储的整数。当整数低于 0 或高于最大值时,它会“循环”回来。所以如果你给一个值为4的LoopingInt加3,最大值为6,则类内部存储的整数为7,但外部请求整数将返回0。

我想要做的是使它可以像使用整数一样使用 LoopingInts。我已经可以将 LoopingInt 分配给 int 对象(即 int x = myLoopingInt),但是我无法将 int 分配给 LoopingInt,因为我不知道如何将具有正确最大值的 LoopingInt 对象传回。我需要左侧值的最大值,但我不知道如何获取它。

【问题讨论】:

  • 我将其命名为 WraparoundInt 或类似名称,因为整数溢出导致值回绕的概念对于许多程序员来说都很熟悉。
  • 仅供参考,您正在构建的是整数同余类的模算术系统;从而形成一个交换环。请参阅 en.wikipedia.org/wiki/Modular_arithmetic 了解可能对您有所帮助的数学背景。
  • 听起来是个好主意。我会这样做的。

标签: c# operators operator-overloading overloading


【解决方案1】:

如果你问如何解决:

LoopingInt myLoopingInt = new LoopingInt(4, 10);
myLoopingInt = x;

这样 myLoopingInt 的 Value 成员被修改,但 MaxValue 成员保持不变,那么我认为这是不可能的。您可以改为设置属性:

myLoopingInt.Value = x;

【讨论】:

  • 现在我想我只能接受这个事实,尽管它可能很烦人。
【解决方案2】:

你可以写一个隐式转换操作符:

public static implicit operator LoopingInt(int i)
{
  return new LoopingInt(i);
}

【讨论】:

  • 嗯,我的想法已经是使用隐式运算符,但是,我需要做的是这样的: myLoopingInt = 5 myLoopingInt 的最大值保持不变。为此,我需要从左侧值中获取该值,但我不知道如何。
【解决方案3】:

好吧,你必须决定你想要的语义:

class LoopingInt32 {
    // details elided

    public LoopingInt32(int maximumValue, int value) { // details elided }

    public static implicit operator LoopingInt32(int x) {
        int maximumValue = some function of x; <-- you implement this
        int value = some other function of x;  <-- you implement this
        return new LoopingInt32(maximumValue, value);
    }
}

我们无法为您决定。

编辑:您所要求的完全是不可能的作业的右侧永远不知道左侧。甚至可能没有左侧(考虑SomeFunctionThatEatsLoopingInt32(5))!

【讨论】:

  • 对不起,我的问题应该更清楚。 maximumValue 与 x 的值无关。它存储在左侧值中,但我不知道如何获取它。我已经知道如何获得价值 - 它只是 x。
  • @Timballisto:哦。那么你要问的是完全不可能的。赋值的右侧永远不知道左侧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 2020-10-19
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多