返回动态生成的数组的方法

今天在写程序时,遇到需要根据数据查询返回的值动态生成数组的方法,.NET中类库中的ArrayList类是可以动态生成数组的类,于是用它写了一个方法大致如下:

None.gif public   int [] Get( int  ID)
ExpandedBlockStart.gifContractedBlock.gif            
dot.gif {
InBlock.gif                
using (SqlConnection conn = new SqlConnection(ConnectionStr))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    SqlCommand cmd 
= new SqlCommand();
InBlock.gif                    cmd.Connection 
= conn;
InBlock.gif                    cmd.CommandText 
= "Select * From Table Where ID='"+ID"'";            
InBlock.gif
InBlock.gif                    conn.Open();
InBlock.gif                    SqlDataReader rdr 
= cmd.ExecuteReader();
InBlock.gif
InBlock.gif                    
int item;
InBlock.gif                    ArrayList result 
= new ArrayList();
InBlock.gif                    
while (rdr.Read())
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        item 
= rdr.GetInt16(0);
InBlock.gif                        result.Add(item);
ExpandedSubBlockEnd.gif                    }

InBlock.gif            
InBlock.gif                    conn.Close();
InBlock.gif
InBlock.gif                    
if (result.Count > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
int count = result.Count;
InBlock.gif                        
int[] arrResult = new int[count];
InBlock.gif                
InBlock.gif                        
for (int i=0;i<count;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            arrResult[i] 
= (int)result[i];
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
return arrResult;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                
return null;
ExpandedBlockEnd.gif            }


这样虽然可以完成我想要的功能,但是在把简单数据类型添加到ArrayList中时都需要装箱,而把ArrayList中的数据取出来赋给int[]的数组元素时则需要拆箱,这样频繁的装箱和拆箱操作会不会降低方法的效率,尤其是返回的数据比较多的情况下,不知道是否有更好的方法?

 

转载于:https://www.cnblogs.com/supersand/archive/2006/04/29/388701.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值