首页 | 互联网 | IT动态 | IT培训 | Cisco | Windows | Linux | Java | .Net | Oracle | 软件测试 | C/C++ | 嵌入式开发 | 存储世界 | 服务器
网络设备 | IDC | 安全 | 求职招聘 | 数字网校 | 网页设计 | 平面设计 | 技术专题 | 电子书下载 | 教学视频 | 源码下载 | 搜索 | 博客 | 论坛
中国IT实验室Dotnet频道
中国IT教育
Google
首页 ASP.NET  C#  XML/WebService ADO.NET VC.NET VB.NET .NET 资讯动态 专题 RSS订阅 讨论 下载
您现在的位置: 中国IT实验室 >> Dotnet >> ASP.NET >> 正文

接口vs. 的实体类

        在设计.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;
        }

        这就是使用接口作为方法的参数,还不使用实体类的好处

【责编:michael】

中国IT教育

相关产品和培训
文章评论
 友情推荐链接
 认证培训
 专题推荐

 ·WEB程序开发--ASP.NET和PHP、JSP究竟学哪个?
 ·五步带你入门XML
 ·关于Java框架技术专题
 ·XML全攻略技术专题
 ·JAVA开源技术介绍专题
 ·Java嵌入式开发之J2ME技术专题
 ·超前体验 Oracle 11g的5个新特性…
 ·揭密使用VB.NET的五个实用技巧
 ·Oracle和SQL Server常用函数对比专题…
 ·展现C#世界 C#程序设计专题…
 今日更新
 社区讨论
 博客论点
 频道精选
 Dotnet频道相关导航