【Translation】介面 vs. 實體類

來源:互聯網
上載者:User

在設計.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;
}

 

這就是使用介面作為方法的參數,還不使用實體類的好處;)

 

原文

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.