运算符重载?
我让自己成为了一个 RSS 阅读器,它可以让我了解最新情况并通知我新节目,或者至少这就是背后的想法。
我创建了一个结构体“SeasonEpisode”,其中包含两个整数(季节+剧集)和一个覆盖 ToString 函数。
我将最新观看的内容存储在本地,然后从 rss 中读取最新内容。但我如何比较季集呢?现在我获取每个整数并比较它们
if( se1.Season >= se2.Season )
if( se1.Episode > se2.Episode || se1.Season > se2.Season )
// new episode!
我真正想要的是
if( se1 > se2 )
// new episode
我可以获得任何帮助吗?
I've made myself a rss reader that keeps me up to date and informs me on new shows, or atleast thats the thought behind.
I've made a struct "SeasonEpisode" that hold two ints (season+episode) and a override ToString function.
I store the latest watched locally and i then read whats the newest is from the rss. But how could I compare SeasonEpisodes? right now I take each of the ints and compare them
if( se1.Season >= se2.Season )
if( se1.Episode > se2.Episode || se1.Season > se2.Season )
// new episode!
What i really want is
if( se1 > se2 )
// new episode
Could i get any help please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两种方法:
IComparable
并使用CompareTo
我建议,您使用两种方式:
There are two ways:
IComparable<T>
and useCompareTo
I suggest, you use both ways:
当我被
NullReferenceException
绊倒时,这是对 Daniel Hilgarth 的改进(这可能是主观的;-))回答。唯一的变化是,如果
>
或<
运算符的第一个参数为 null,它会处理null
:As i tripped over a
NullReferenceException
, here's an improvement (well this may be subjective ;-)) to Daniel Hilgarth's answer.The only change is that it handles
null
s in case the first argument to the>
or<
operator is null:您可以实现
IComparer
界面如果您希望一个类与该类的另一个实例具有可比性,您可以实现 IComparable。在这种情况下,这可能就是您想要的。
如果您需要一个比较两个对象的类,请实现
IComparer
。You can implement the
IComparer<T>
interfaceYou can implement
IComparable
if you want a class to be comparable to another instance of that class. Which is probably what you want, in this case.Implement
IComparer
if you need a class that compares two objects.