2010-08-22 36 views
1

即时尝试从数据库动态获取数据。我已经list<T> select<T>()方法......我的继承人问题,我可以在这里使用的DataReader得到DATAS是代码:如何在列表中添加类型<T> in c#4,0

public list<T> Select<T>() 
{ 
    Type type = typeof(T); 
    ... 
    ... 
    using (SqlConnection connection = new SqlConnection(ConnectionString)) 
    { 
     try 
     { 
       SqlCommand sqlCommand = new SqlCommand(selectCommand, connection); 
       connection.Open(); 
       SqlDataReader sqlReader = sqlCommand.ExecuteReader(); 
       while (sqlReader.Read()) 
       { 
        foreach (PropertyInfo property in type.GetProperties()) 
        { 
         property.SetValue(property.Name,(PropertyInfo)sqlReader[property.Name],null); 

        } 
        typeList.Add((T)Convert.ChangeType(type,typeof(T))); 
       } 
       sqlReader.Close(); 
     } 
     catch (Exception ex) 
     { 
       string exc = ex.Message; 
     } 
     finally 
     { 
       connection.Close(); 
     } 
    } 
    return typeList; 
} 

我可以得到的数据,但我不能把它分配给我喜欢的类型,所以我不能加我型到我的类型串,可以帮助我

+0

请编辑你质疑,请选择您的代码,然后按在按钮的代码编辑(101 \ 010)。 – 2010-08-22 10:05:47

+0

您的代码不完整,缺少typeList的声明。 – 2010-08-22 10:08:43

回答

0

你想在这里转换什么样的数据类型?你可能应该根据查询选择数据,这看起来像你试图将整个数据库存储在一个随机提供的类型中。您可能试图将文本存储在双精度表中...

如果您只是想要存储数据库中的所有数据,请使用DataSet或DataTable。

此外你在这里做什么?

property.SetValue(property.Name,(PropertyInfo)sqlReader[property.Name],null); 

貌似你试图改变所请求的类型的属性名称...

1

能分配属性类型之前,您需要初始化它:

T instance = Activator.CreateInstance<T>(); 
foreach (PropertyInfo property in type.GetProperties()) 
{ 
    property.SetValue(instance, sqlReader[property.Name], null); 
} 
typeList.Add(instance); 

同时将SqlCommand包装在using区块中,以正确处置它。另一种说法是,您不需要在finally块中连接.Close(),这将自动通过Dispose方法完成,因为您已经将连接包装在using块中。

+0

非常感谢我找到了答案,但这看起来也很有用 – 2010-08-24 08:49:49

1

看起来你想为每个数据库行创建一个类型为T的对象。

那么你可能会约束你的泛型类的空构造函数:

public List<T> Select<T>() where T : new() 

,那么你可以创建新的T的

while (sqlReader.Read()) 
{ 
    T item = new T(); 
    foreach (PropertyInfo property in type.GetProperties()) 
    { 
     // Note the first parameter "item" 
     property.SetValue(item, sqlReader[property.Name], null); 
    } 
    typeList.Add(item); 
} 
+0

非常感谢我找到了和你一样的答案 – 2010-08-24 08:49:15

相关问题