【发布时间】:2015-06-30 18:04:30
【问题描述】:
我正在尝试将 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))) : "";
}
我已经完成了这个简单的更改来更改它的返回类型,但我不确定如何正确转换我的对象,以便将我的 DataTable 转换为泛型类型。
public static T getDBSpecifiedType<T>(string columnName, DataTable table, int index = 0)
{
return Convert.ChangeType(table.Rows[index][columnName], typeof(T));
}
错误:
无法将类型“object”隐式转换为“T”。存在显式转换(您是否缺少演员表?)
该功能在我看来很简单,错误消息并不复杂我只是缺少一些东西来让我的功能正常工作。
感谢您的帮助,西蒙
【问题讨论】:
-
错误信息是什么?也许您没有先检查索引和/或列名是否存在?
-
错误出现在 getDBSpecifiedType 函数中:“无法将类型 'object' 隐式转换为 'T'。存在显式转换(是否缺少强制转换?)”