帮助C#中的隐式运算符重载

时间:2010-11-20 22:56:13

标签: c# operators operator-overloading overloading

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

我想要做的就是这样我可以使用LoopingInts,就好像它们是整数一样。我已经可以将LoopingInts分配给int对象(即int x = myLoopingInt),但我不能将一个int分配给一个LoopingInt,因为我无法弄清楚如何传回一个具有正确最大值的LoopingInt对象。我需要左手值的最大值,但我不知道如何得到它。

3 个答案:

答案 0 :(得分:2)

如果你问如何修复:

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

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

myLoopingInt.Value = x;

答案 1 :(得分:0)

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

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))!

答案 2 :(得分:0)

您可以编写隐式转换运算符:

public static implicit operator LoopingInt(int i)
{
  return new LoopingInt(i);
}
相关问题