开发者

Help with implicit operator overload in C#

I'm trying to make a class called LoopingInt. It stores two integers, one being the maximum value of the integer, and the other being a stored integer. When the integer falls below 0 or above the maximum value, it "loops" back around. So if you add 3 to a LoopingInt with a value of 4, and the max value is 6, the internally stored integer in the class will be 7, but asking for the int开发者_C百科eger externally will return 0.

What I want to do is make it so I can work with LoopingInts as if they were integers. I can already assign LoopingInts to int objects (ie int x = myLoopingInt), but I can't assign an int to a LoopingInt because I can't figure out how to pass back a LoopingInt object with the right maximum value. I need the maximum value from the left-hand value, but I don't know how to get it.


If you're asking how to fix:

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

so that myLoopingInt's Value member is modified but the MaxValue member stays the same then I don't think its possible. You can set a property instead:

myLoopingInt.Value = x;


You can write an implicit conversion operator:

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


Well, you have to decide the semantics that you want:

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);
    }
}

We can't decide this for you.

Edit: What you're asking for is completely impossible The right-hand-side of an assignment never knows about the left-hand-side. There might not even be a left-hand-side (consider SomeFunctionThatEatsLoopingInt32(5))!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜