Skip to main content
 首页 » 编程设计

c#之是否有理由在使用后将对象设置为空

2024年02月13日12lyj

<分区>

我看到很多代码在 finally 部分或方法末尾将对象设置为 null,例如:

        [WebMethod] 
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
        public void buildUpdates(int batchId, string mkt) 
        { 
            aplUpdate oDU; 
            DataSet ds; 
            DataTable dtTbls; 
            DataTable dtData; 
            List<dbVer> resp; 
 
            try 
            {  
                oDU = new WEB_APL.APL.aplUpdate(MyWeb.Properties.Settings.Default.DBCon); 
 
                ds = new DataSet();  
                ds.DataSetName = batchId.ToString(); 
                dtTbls = oDU.getDetails(true); 
                resp=GetDBVersions(); 
 
                foreach (DataRow dr in dtTbls.Rows) 
                { 
                    .....               
                } 
                ds.WriteXml(HttpContext.Current.Server.MapPath("~") + "\\" + ds.DataSetName + ".xml", XmlWriteMode.WriteSchema); 
 
            } 
            catch (Exception ex) 
            { 
                throw ex; 
            } 
            finally 
            { 
               oDU = null; 
               ds=null; 
               rest=null; 
               dtTbls=null; 
               dtData=null; 
            } 
        } 

我认为这是不必要的,因为过期对象将由 .NET 垃圾收集器自动处理。

为什么应该重置为 null?