帮助解决 C# 中的隐式运算符重载
我正在尝试创建一个名为 LoopingInt 的类。它存储两个整数,一个是整数的最大值,另一个是存储的整数。当整数低于 0 或高于最大值时,它会“循环”回来。因此,如果将 3 添加到值为 4 的 LoopingInt,并且最大值为 6,则类中内部存储的整数将为 7,但外部请求整数将返回 0。
我想做的是使其成为所以我可以像使用整数一样使用 LoopingInts。我已经可以将 LoopingInts 分配给 int 对象(即 int x = myLoopingInt),但我无法将 int 分配给 LoopingInt,因为我不知道如何传回具有正确最大值的 LoopingInt 对象。我需要左侧值的最大值,但我不知道如何获取它。
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 integer 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您询问如何修复:
以便 myLoopingInt 的 Value 成员被修改,但 MaxValue 成员保持不变,那么我认为这是不可能的。您可以设置一个属性:
If you're asking how to fix:
so that myLoopingInt's
Value
member is modified but theMaxValue
member stays the same then I don't think its possible. You can set a property instead:您可以编写隐式转换运算符:
You can write an implicit conversion operator:
好吧,您必须决定您想要的语义:
我们无法为您决定。
编辑:你所要求的是完全不可能的作业的右侧永远不知道左侧。甚至可能没有左侧(考虑
SomeFunctionThatEatsLoopingInt32(5)
)!Well, you have to decide the semantics that you want:
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)
)!