我想將DataTable值轉換爲指定的泛型類型,但出現錯誤。將DataTable值轉換爲通用類型
我已經編程了一個類似的函數,它工作正常。它返回一個字符串,我可以用它來放入一個TextBox或一個ComboBox,我試圖修改它來改變它的返回類型。那就是:
/// <summary>
/// Get Value from a DataTable
/// </summary>
/// <typeparam name="T">Type of Value to get from the DataTable : int | Single | string | double</typeparam>
/// <param name="columnName">Name of the column in the DataTable</param>
/// <param name="table">The DataTable</param>
/// <returns>Get the string value to put in a Textbox</returns>
public static string getDB<T>(string columnName, DataTable table, int index = 0)
{
bool isEmpty = String.IsNullOrEmpty(Convert.ToString(table.Rows[index][columnName]));
return (!isEmpty) ? Convert.ToString(Convert.ChangeType(table.Rows[index][columnName], typeof(T))) : "";
}
我已經這樣做了簡單的改變來改變它的返回類型,但我不確定如何正確地投我的對象,我在我的數據錶轉換爲通用類型。
public static T getDBSpecifiedType<T>(string columnName, DataTable table, int index = 0)
{
return Convert.ChangeType(table.Rows[index][columnName], typeof(T));
}
Error:
Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?)
的功能似乎簡單,我的眼睛和錯誤消息並不複雜,我只是失去了一些東西讓我的功能工作。
感謝您的幫助,西蒙
什麼是錯誤信息?也許你沒有檢查索引和/或列名是否先存在? – maksymiuk
錯誤在getDBSpecifiedType函數中:「不能隱式地將類型'object'轉換爲'T'。存在明確的轉換(你是否缺少一個轉換?)」 – Slimsim3