看了一段代码public SqlDataReader GetMyDocument(string UserName,int RightCode)
{
Database data = new Database();
SqlDataReader dataReader = null;
// 执行存储过程,并返回SqlDataReader对象
SqlParameter[] prams = {
   data.MakeInParam("@UserName" , SqlDbType.VarChar , 300, UserName),
   data.MakeInParam("@RightCode",SqlDbType.Int,4,RightCode)
   };

try 
{
data.RunProc("sp_GetMyNewDoc",prams,out dataReader);
return dataReader; }
catch(Exception ex)
{
Error.Log(ex.ToString());
throw new Exception("读取我的文档出错!",ex);
}
finally
{
data    = null;
dataReader = null;
}
}finally里已经把dataReader成null了那返回的dataReader还可能有东西吗?麻烦解释一下!谢谢

解决方案 »

  1.   

    读取datareader的时候是不能跟db断开的,用过之后必须close
    如果没什么特殊要求,建议用dataset,或者arraylist之类的做数据源
      

  2.   

    如果执行正确值就已经传回去了,最后设为null只是释放资源而已
      

  3.   

    在try 中已经返回一个有数据的Reader 然后最后再释放无用的资源
      

  4.   

    看看这个些代码:也许可以帮你!public static SqlDataReader ExecuteGetDataReader(string sqlcomm)
    {
    Open();
    SqlDataReader dr = null;
    try
    {
    SqlCommand dc=new SqlCommand(sqlcomm,con);
    dr = dc.ExecuteReader();
    return dr;
    }
    catch(SqlException ex)
    {
    //EventLog.WriteEntry(webconfig.EVENT_LOG_SOURCE, ex.Message.ToString());
    throw new Exception("SQL错误:"+ ex.Message);
    }
    }
    public static void Open()
    {
    if (con==null)
    {
    con = new SqlConnection(webconfig.SQL_Conntion);
    con.Open();
    }
    else
    {
    con.Close();
    con = new SqlConnection(webconfig.SQL_Conntion);
    con.Open();
    }
    }
      

  5.   

    按理说SqlDataReader是引用类型,这样的话当=null时,返回的应该就是null了
    为什么最后还是得到了值呢?
      

  6.   

    执行顺序是先return dataReader;
    然后再执行finally中的赋值,也就是说,当你给dataReader赋值的时候,这个对象已经返回给调用它的函数了,fianlly只起了一个清理的作用,因此会得到那个值
      

  7.   

    返回的dataReader还有东西
    原因涉及到.NET的GC机制、引用类型的特点。
    1.首先执行的是return代码,返回dataReader的引用地址
    2.执行finally代码,将dataReader 的指针指向空引用(注意,dataReader原指针指向的对象并没有清除)
    3.调用代码得到dataReader原指针
    4.GC判断出dataReader原指针依然被使用,不回收dataReader原指针指向的对象因此,返回的dataReader还有东西大家明白了?
      

  8.   

    补充说明:
    如果你的返回值是DataSet并在finally中执行了DataSet.Dispose
    你依然可以得到正确的返回值