[英]how to implement Interface in class C#
我有两个接口IAppointment and IAppointments : IList<IAppointment>
第二类中的IAppointment and IAppointments : IList<IAppointment>
我有3个成员
public interface IAppointments : IList<IAppointment>
{
bool Load();
bool Save();
IEnumerable<IAppointment> GetAppointmentsOnDate(DateTime date);
}
其中我只能实现Appointments类中的前2个,并且使用第3种方法尝试的任何方法都会出错,并且我总是会遇到相同的14个错误(关于“ Appointments未实现接口成员IAppointment.GetEnumerator(),。”。计数,。删除,。包含和其他一些
也是这另一个
public interface IAppointment
{
DateTime Start { get; }
int Length { get; }
string DisplayableDescription { get; }
bool OccursOnDate(DateTime date);
}
在这里我可能也需要在一个类中实现这些功能,对不起我的不好的解释,但也许我还不了解实际的问题
PS两个接口/类都在另一个没有错误运行的局部类中使用
更新:
我现在唯一的问题是我不知道如何实现IAppointment的第一个成员(返回的类型应该是什么?因为约会的开始时间例如12:00),我认为几乎其他一切都很好
PS2谢谢你们到目前为止的帮助!
因为IAppointments
接口是从IList<T>
派生的,所以Appointments
类必须实现IList<T>
所有成员以及该接口派生的任何接口。 GetEnumerator()
来自IEnumerable<T>
,它是IList<T>
派生的。
除非使用诸如composition这样的方法,否则在IAppointments
上公开IList<T>
属性以获取要在其上执行诸如索引等操作的列表,否则将需要实现IList<T>
, ICollection<T>
Appointments
类中的ICollection<T>
和IEnumerable<T>
。
我认为您最好的解决方案是这样的:
public interface IAppointments
{
IList<IAppointment> TheAppointments { get; }
bool Load();
bool Save();
IEnumerable<IAppointment> GetAppointmentsOnDate(DateTime date);
}
然后,您将访问Appointments
类中的TheAppointments
属性,以提供实现GetAppointmentsOnDate(DateTime)
。
如注释中所述,您不仅可以为接口实现一组特定的方法,而且当IAppointments
接口派生自IList<IAppointment>
,实现类还必须实现IList
接口的所有成员,除了IAppointments
的成员。
下面的类定义将实现此目的:
using System.Collections.ObjectModel;
public class Appointments : Collection<IAppointment>, IAppointments
{
public bool Load()
{
return true;
}
public bool Save()
{
return true;
}
public IEnumerable<IAppointment> GetAppointmentsOnDate(DateTime date)
{
return new List<IAppointment>();
}
}
这将使您能够访问IList
上的所有方法(因为Collection<T>
实现了IList<T>
)和IAppointment
允许您编写如下代码(假设实现IAppointment
的类称为Appointment
而我已经明确了意图)代码正确):
var appointments = new Appointments();
if (appointments.Load() == true) // from IAppointments
{
var totalAppointmentCount = appointments.Count(); // from IList through Collection<T>
var numberOfAppointmentsToday = appointments.GetAppointmentsOnDate(DateTime.Now.Date).Count(); // from IAppointments
var newAppointment = new Appointment();
appointments.Add(newAppointment); // from IList through Collection<T>
if (appointments.Save() == true) // from IAppointments
{
Console.WriteLine("All saved, happy days!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.