我意识到我的问题不清楚,所以我添加了更多信息。 我一直在寻找无处不在的解决方案,但我找不到。我不知道如何使用重写运算符==,= !、 Gethashcode和equal方法。请帮我。
公共静态运算符bool ==(Time lhs,Time rhs)–此方法将覆盖equal运算符。如果两个参数之间的差小于15分钟,则此方法将返回true,否则返回false。该方法在Theater类的PrintShows(Time time)方法中使用。
PrintShows(Time time)–此公共方法将一个时间对象作为参数,并显示与该时间对象的小时值匹配的所有节目。只有在Time类中正确实现了==运算符后,才能正常工作
我正在尝试使用PrintShows(Time time)方法来显示符合特定条件的特定对象。
using System;
using System.Collections.Generic;
using static System.Console;
namespace sufferingg
{
class Theatre
{
private List<Show> shows;
private string name;
public Theatre(string name)
{
this.name = name;
shows = new List<Show>();
}
public void AddShow(Show show)
{
shows.Add(show);
}
public void PrintShows(Time time)
{
WriteLine("shows at {0}", time);
WriteLine("-------------------------------------------------");
List<Show> foundShows = shows.FindAll(x => x.Time == time);
foreach (Show a in foundShows)
{
WriteLine(a);
}
WriteLine("-------------------------------------------------");
WriteLine("The number of All shows: " + foundShows.Count +"\n");
}
}
class Time
{
public int Hours { get; }
public int Minutes { get; }
public Time(int hours, int minutes)
{
this.Hours = hours;
this.Minutes = minutes;
}
public override string ToString()
{
if (Minutes < 10)
return Hours + ":0" + Minutes;
else
return Hours + ":" + Minutes;
}
//No idea how to use it properly
public static bool operator ==(Time onehs, Time rhs)
{
int overallDiff = Math.Abs(onehs.Hours - rhs.Hours) * 60 +
Math.Abs(onehs.Minutes - rhs.Minutes);
return overallDiff < 15;
}
public static bool operator !=(Time onehs, Time rhs)
{
int overallDiff = (onehs.Hours - rhs.Hours) * 60 + onehs.Minutes - rhs.Minutes;
if (overallDiff < 15)
return (onehs == rhs);
else
return false;
}
//I have no idea how to use GetHasCode and Equals...
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
class Show
{
public Movie Movie { get; }
public Time Time { get; }
public Show(Movie movie, Time time)
{
this.Movie = movie;
this.Time = time;
}
public override string ToString()
{
return "Movie: " + Movie.Title + "\n"+
"Time: " + Time + "\n";
}
}
class Movie
{
public int Length { get; }
public string Title { get; }
public Movie(string name, int length)
{
this.Title = name;
this.Length = length;
}
}
class Program
{
static void Main(string[] args)
{
Theatre eglinton = new Theatre("Cineplex");
Movie terminator = new Movie("Judgement Day", 105);
Movie trancendence = new Movie("Transendence", 120);
Movie americanbeauty= new Movie("americanbeauty, 105);
eglinton.AddShow(new Show(terminator, new Time(13, 45)));
eglinton.AddShow(new Show(trancendence, new Time(18, 5)));
eglinton.AddShow(new Show(americanbeauty, new Time(13, 55)));
//display 2 object
eglinton.PrintShows(new Time(13, 55));
}
}
}
程序应显示
电影:终结者 时间:13:45
电影:Americanbeauty 时间:13:55
全部显示的数目:2
但仅显示
电影:Americanbeauty 时间:13:55
全部显示的数目:1