[英]Passing interface variable through a class constructor in C#
我在 Testdome.com 上練習C# ,我解決了下面的編碼練習(AlertService),但仍然不相信第 3 點和第 4 點的目的:
重構 AlertService 和 AlertDAO 類:
1- 創建一個名為 IAlertDAO 的新接口,其中包含與 AlertDAO 相同的方法。
2- AlertDAO 應該實現 IAlertDAO 接口。
3- AlertService 應該有一個接受 IAlertDAO 的構造函數。
4- RaiseAlert 和 GetAlertTime 方法應使用通過構造函數傳遞的 object。
這是我寫的代碼,我添加了AlertDAO實現的構造函數和接口,最后編譯沒問題,但我需要知道這是否是解決它的正確方法:
public class AlertService
{
private readonly AlertDAO storage = new AlertDAO();
//Constructor
public AlertService(IAlertDAO alert)
{
storage = (AlertDAO)alert;
}
public Guid RaiseAlert()
{
return this.storage.AddAlert(DateTime.Now);
}
public DateTime GetAlertTime(Guid id)
{
return this.storage.GetAlert(id);
}
static void Main(string[] args)
{
IAlertDAO alertDao = new AlertDAO();
AlertService alert = new AlertService(alertDao);
Guid id = alert.RaiseAlert();
Console.WriteLine(alert.GetAlertTime(id));
Console.ReadKey();
}
}
public class AlertDAO : IAlertDAO
{
private readonly Dictionary<Guid, DateTime> alerts = new Dictionary<Guid, DateTime>();
public Guid AddAlert(DateTime time)
{
Guid id = Guid.NewGuid();
this.alerts.Add(id, time);
return id;
}
public DateTime GetAlert(Guid id)
{
return this.alerts[id];
}
}
public interface IAlertDAO
{
Guid AddAlert(DateTime time);
DateTime GetAlert(Guid id);
}
很少有人指出。 storage
應該是IAlertDAO
類型,因此不需要在構造函數中進行強制轉換。 無需在其聲明中對其進行new
。
public class AlertService
{
private readonly IAlertDAO storage;
//Constructor
public AlertService(IAlertDAO alert)
{
storage = alert;
}
public Guid RaiseAlert()
{
return this.storage.AddAlert(DateTime.Now);
}
public DateTime GetAlertTime(Guid id)
{
return this.storage.GetAlert(id);
}
static void Main(string[] args)
{
IAlertDAO alertDao = new AlertDAO();
AlertService alert = new AlertService(alertDao);
Guid id = alert.RaiseAlert();
Console.WriteLine(alert.GetAlertTime(id));
Console.ReadKey();
}
}
public class AlertDAO : IAlertDAO
{
private readonly Dictionary<Guid, DateTime> alerts = new Dictionary<Guid, DateTime>();
public Guid AddAlert(DateTime time)
{
Guid id = Guid.NewGuid();
this.alerts.Add(id, time);
return id;
}
public DateTime GetAlert(Guid id)
{
return this.alerts[id];
}
}
public interface IAlertDAO
{
Guid AddAlert(DateTime time);
DateTime GetAlert(Guid id);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.