2010-08-22 70 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

相關問題