簡體   English   中英

如何在C#類中實現Interface

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM