随笔- 28  文章- 0  评论- 63 

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

public int[] Get(int ID)
            
{
                
using (SqlConnection conn = new SqlConnection(ConnectionStr))
                
{
                    SqlCommand cmd 
= new SqlCommand();
                    cmd.Connection 
= conn;
                    cmd.CommandText 
= "Select * From Table Where ID='"+ID"'";            

                    conn.Open();
                    SqlDataReader rdr 
= cmd.ExecuteReader();

                    
int item;
                    ArrayList result 
= new ArrayList();
                    
while (rdr.Read())
                    
{
                        item 
= rdr.GetInt16(0);
                        result.Add(item);
                    }

            
                    conn.Close();

                    
if (result.Count > 0)
                    
{
                        
int count = result.Count;
                        
int[] arrResult = new int[count];
                
                        
for (int i=0;i<count;i++)
                        
{
                            arrResult[i] 
= (int)result[i];
                        }

                        
return arrResult;
                    }

                }


                
return null;
            }


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

 

 posted on 2006-04-29 15:11 寒带鱼 阅读(442) 评论(4) 编辑 收藏

#1楼[楼主]   回复 引用 查看   
 寒带鱼       | 2006-04-29 15:49
@教父
首先感谢你的留言,欢迎和我交流关于.NET技术的问题,你可以在这里留言,或发E-Mail给我supersandpro@hotmail.com,谢谢

#2楼   回复 引用 查看   
 天轰穿       | 2006-04-30 21:33
建议:单独引入命名空间,你这样写,少当然没有什么,但是多了的话可能多少会有点影响阅读,呵呵!不是大问题,只是我觉得看了就回才对得起你撒!

至于好方法,我试了几下,没有试出来,惭愧ing...

#3楼[楼主]   回复 引用 查看   
 寒带鱼       | 2006-05-02 11:24
@天轰穿
谢谢你的回复,有好办法的时候这个方法我还要修改

#4楼[楼主]   回复 引用 查看   
 寒带鱼       | 2006-05-09 18:00
ArrayList与数组转换:

整型数组:
例1:
ArrayList List = new ArrayList();
List.Add(1);
List.Add(2);
List.Add(3);

Int32[] values = (Int32[])List.ToArray(typeof(Int32));

例2:
ArrayList List = new ArrayList();
List.Add(1);
List.Add(2);
List.Add(3);

Int32[] values = new Int32[List.Count];
List.CopyTo(values);

对象数组:
Object[] personArrayFromList = (Object[])personList.ToArray(typeof(Object));