我正在尝试将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));
}
错误:
无法将类型为“对象”的值隐式转换为“T”。存在显式的转换(是否缺少强制转换?)
在我看来,这个函数似乎很简单,错误信息也不复杂,我只是缺少一些东西让我的函数工作起来。
谢谢任何帮助,Simon