运算符超载? [英] Operator overloading?
本文介绍了运算符超载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使自己成为RSS读者,可以随时了解我的最新情况,并在新节目或不曾有过的最新消息方面通知我.
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.
我制作了一个结构"SeasonEpisode",其中包含两个整数(季节+集)和一个重写ToString函数.
I've made a struct "SeasonEpisode" that hold two ints (season+episode) and a override ToString function.
我将最新观看的内容存储在本地,然后从rss中读取最新的内容.但是我该如何比较SeasonEpisodes?现在,我将每个int进行比较
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!
我真正想要的是
if( se1 > se2 )
// new episode
请问有什么需要吗?
推荐答案
有两种方法:
- 实施
IComparable<T>
并使用CompareTo
- 重载大于和小于运算符的内容
- Implement
IComparable<T>
and useCompareTo
- Overload the greater and less than operators
我建议您同时使用以下两种方式:
I suggest, you use both ways:
public class SeasonEpisode : IComparable<SeasonEpisode>
{
public int CompareTo(SeasonEpisode other)
{
if(other == null)
return 1;
if(Season == other.Season)
{
if(Episode == other.Episode)
return 0;
else if(Episode < other.Episode)
return -1;
else
return 1;
}
else if(Season < other.Season)
return -1;
else
return 1;
}
public static bool operator <(SeasonEpisode e1, SeasonEpisode e2)
{
return e1.CompareTo(e2) < 0;
}
public static bool operator >(SeasonEpisode e1, SeasonEpisode e2)
{
return e1.CompareTo(e2) > 0;
}
}
这篇关于运算符超载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文