为了账号安全,请及时绑定邮箱和手机立即绑定

奇怪的SqlDataReader

奇怪的SqlDataReader

C#
跃然一笑 2018-12-16 17:09:35
问题来源于一个非常初级的错误,在写一个数据库访问代码时 不小心写成了SqlDataReader reader=new SqlDataReader()结果编译器报错:“未定义构造函数”,谁都知道SqlDataReader是不能这样被实例化的,改成SqlDataReader reader=cmd.ExecuteDataReader()就完,但是心中的疑问确不由产生,第一是个编译器报的错“未定义构造函数”,开始以为我没有写实参,但是intellsence告诉我根本就没有什么参数!诶这就奇怪了,没有参数的构造函数不是系统就默认有的嘛,那为什么不能这样new?还有就是既然不能new 那在ExecuteDataReader()中这个SqlDataReader的对象是如何生成的???请高人指点迷津!
查看完整描述

2 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

MSDN帮助原文: 若要创建 SqlDataReader,必须调用 SqlCommand 对象的 ExecuteReader 方法,而不要直接使用构造函数。 ExecuteDataReader() 的函数体: public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; SqlDataReader reader; IntPtr ptr; Bid.ScopeEnter(out ptr, "<sc.SqlCommand.ExecuteReader|API> %d#", this.ObjectID); try { statistics = SqlStatistics.StartTimer(this.Statistics); reader = this.ExecuteReader(CommandBehavior.Default, "ExecuteReader"); } finally { SqlStatistics.StopTimer(statistics); Bid.ScopeLeave(ref ptr); } return reader; } SqlDataReader的构造函数: internal SqlDataReader(SqlCommand command, CommandBehavior behavior) { this._recordsAffected = -1; this.ObjectID = Interlocked.Increment(ref _objectTypeCount); this._command = command; this._commandBehavior = behavior; if (this._command != null) { this._timeoutSeconds = command.CommandTimeout; this._connection = command.Connection; if (this._connection != null) { this._statistics = this._connection.Statistics; this._typeSystem = this._connection.TypeSystem; } } this._dataReady = false; this._metaDataConsumed = false; this._hasRows = false; this._browseModeInfoConsumed = false; } 不是没有构造函数,不给你用罢了

查看完整回答
反对 回复 2018-12-20
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

private SqlDataReader(){} 这样就不能使用构造函数了

查看完整回答
反对 回复 2018-12-20
  • 2 回答
  • 0 关注
  • 585 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信