[已解决问题] 奇怪的SqlDataReader
提问时间: 2008-04-17 11:43
悬赏分:10 浏览:299 次
问题来源于一个非常初级的错误,在写一个数据库访问代码时 不小心写成了SqlDataReader reader=new SqlDataReader()结果编译器报错:“未定义构造函数”,谁都知道SqlDataReader是不能这样被实例化的,改成SqlDataReader reader=cmd.ExecuteDataReader()就完,但是心中的疑问确不由产生,第一是个编译器报的错“未定义构造函数”,开始以为我没有写实参,但是intellsence告诉我根本就没有什么参数!诶这就奇怪了,没有参数的构造函数不是系统就默认有的嘛,那为什么不能这样new?还有就是既然不能new 那在ExecuteDataReader()中这个SqlDataReader的对象是如何生成的???请高人指点迷津!
提问者:张鲁华 - 初学一级
最佳答案
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;
}

 不是没有构造函数,不给你用罢了

 
2008/4/17 12:56:14 回答者:杨连国


提问者对于答案的评价:谢谢! 原来是访问权限的问题
其它回答(1)
private SqlDataReader(){}
这样就不能使用构造函数了
4个月前   回答者:Dove.Net - 初学一级
评论
4个月前   Dove.Net :
单件模式中经常用到
4个月前   张鲁华 :
不对!假如把构造函数声明为private 那编译器报的是“不可访问,因为他受保护级别限制”的错,而上面报的是“未定义构造函数”。不是一回事吧!
4个月前   张鲁华 :
Singleton 不就是把 构造函数声明为private或者是static嘛 
   您需要登录以后才能回答!
我的问题    我要提问


快到期问题

> 问题排行榜

有不合适内容,建议去除