在設計.net程式架構的時候,我更傾向於使用介面而不是實體類在作為函數的參數。
我們來看看下面這個例子:
第一個方法public IList<Article> Get(),他調用資料庫,並得到一個包含了查詢結果資料集合的SqlDataReader,然後調用第二個方法private IList<Article> FillArticles(SqlDataReader reader)的將SqlDataReader中的結果添加到IList<Article>中。
public IList<Article> Get()
{
SqlConnection connection = new SqlConnection(_connectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetAllArticles";
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleResult);
return FillArticles(reader);
}
private IList<Article> FillArticles(SqlDataReader reader)
{
List<Article> articles = new List<Article>();
while (reader.Read())
{
Article article = new Article();
article.ArticleID = (int)reader["ArticleID"];
article.Title = reader["Title"];
article.Body = reader["Body"];
article.Published = (DateTime)reader["Published"];
articles.Add(article);
}
return articles;
}
通過上面這個例子你可以發現,FillArticles方法需要一個SqlDataReader (這是一個實體類)。好,現在需求變了,現在資料都儲存在了XML檔案中,這個時候,我們得到就是XmlDataReader(實際沒有這個類型)而不是SqlDataReader了。很不幸,你唯一能做的就是修改這塊的原始碼。
那麼,我們怎麼樣才能避免這樣的問題呢?我們假設SqlDataReader和 XmlDataReader都實現了IDataReader介面。我們只需要把代碼修改成如下的樣子即可解決開始遇到的問題了:
private IList<Article> FillArticles(IDataReader reader)
{
List<Article> articles = new List<Article>();
while (reader.Read())
{
Article article = new Article();
article.ArticleID = (int)reader["ArticleID"];
article.Title = reader["Title"];
article.Body = reader["Body"];
article.Published = (DateTime)reader["Published"];
articles.Add(article);
}
return articles;
}
這就是使用介面作為方法的參數,還不使用實體類的好處;)
原文