• Interfaces Topic


            Interfaces Wow, 在开发时、架构时、思考时,Interfaces都是我们这族人常常使用的,

    在开发工作中,我常常用Interfaces作为参数类型用于方法的signatures.

          此贴就是解释为什么choose to do this,& the benefits of coding...

    让我们来看两个操作数据的方法

    第一个方法:创建数据库的连接,发出请指令,查询想要的数据结果返回一个结果。

    第二个方法:通过while(reader.Read())填充一个IList<Entity>.

    代码如下:

    
    
    
     1public IList<Article> Get() {  
     2    SqlConnection connection = new SqlConnection(_connectionString);  
     3    SqlCommand command = new SqlCommand();   
     4    command.Connection = connection;  
     5    command.CommandType = CommandType.StoredProcedure; 
     6    command.CommandText = "GetAllArticles";    
     7    SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleResult); 
     8    return FillArticles(reader);
     9}

    10
    11private IList<Article> FillArticles(SqlDataReader reader) {
    12    List<Article> articles = new List<Article>();
    13    while (reader.Read()) {
    14        Article article = new Article();
    15        article.ArticleID = (int)reader["ArticleID"];
    16        article.Title = reader["Title"];
    17        article.Body = reader["Body"];
    18        article.Published = (DateTime)reader["Published"];
    19        articles.Add(article);
    20    }

    21    return articles;
    22}

    23
           FillArticles方法是期待一个具体类与其连接(及:SqlDataReader).
           现在让我们来假设,如果你的数据不在存储于数据库,而把数据源改为其他方式Store,比如XML Files.
     
           这时一般都是重新写一个构建一个Get方法,然后以 to handle Xml access的方式,重新pass 一个
     
     XmlDataReader to the FillArticles()方式。
           但不幸的是,你将得到一个Error Information, 因为你的FillArticles()是期待一个SqlDataReader与其互访的。
           那我们如果解决此问题呢?
           Well,very easy,因为SqlDataReader & XmlDataReader都是 implement an Interface,
    此Interface名为IDataReader.接下来只要Changing the paremeter type from SqlDataReader to 
    IDataReader即可,这样你就可以不需要更改,或者重新此方法。是不是很不错的选择呢。
    代码如下:
    
     1 private IList<Article> FillArticles(IDataReader reader) {
     2     List<Article> articles = new List<Article>();
     3     while (reader.Read())
     4     {
     5         Article article = new Article();
     6         article.ArticleID = (int)reader["ArticleID"];
     7         article.Title = reader["Title"];
     8         article.Body = reader["Body"];
     9         article.Published = (DateTime)reader["Published"];
    10         articles.Add(article);
    11     }
    12     return articles;
    13 }
    14 
    其实当然看清事物的本质是什么,有时可以帮助自己很好的认识它,同时更可以很好使用它,即方便开发etc.
           另外在VS当中好像有一个key short(Alt+ Ctrl +J)可以查找,查看具体类的Base Type.
          当然如果你安装了ReSharper, 它也是可以及时告知你。
    以上就是Inerfaces & Concrete 之的话题。
    有关于Interface与It的话题还是比较多的,下面我给几个资源
  • 相关阅读:
    fork子进程
    多输入使用多线程
    多输入select
    多输入之轮询
    开启telnet
    slickedit编译调试linux应用程序
    电子书框架
    通用Makefile
    STDIN_FILENO和stdin
    libiconv交叉编译提示arm-none-linux-gnueabi-gcc
  • 原文地址:https://www.cnblogs.com/RuiLei/p/1270661.html
Copyright © 2020-2023  润新知