将DataTable的值转换为通用类型

4

我正在尝试将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


错误信息是什么?也许你没有先检查索引和/或列名是否存在? - maraaaaaaaa
错误出现在 getDBSpecifiedType 函数中: "无法隐式将类型 'object' 转换为 'T'。存在显式转换 (是否缺少强制转换?)" - Slimsim3
2个回答

2

在Stack Overflow上寻找更多答案后,我最终使用了以下内容:

public static Nullable<T> getDBSpecifiedType<T>(string columnName, DataTable table, int index = 0)
{
    if (getDB<T>(columnName, table, index) != String.Empty)
    return (T)Convert.ChangeType(table.Rows[index][columnName], typeof(T));

    return null;
}

通过调用我的原始函数,我能够确定DataTable值是否为空,并返回null(我使用了可空类型,因为例如字符串与双精度浮点数的默认值不同)。如果不为空,我可以将其强制转换为泛型类型并返回结果。

1
这种 T 类型转换模式对我也起作用了:
public static T getDBSpecifiedType<T>(string columnName, DataTable table, int index = 0)
{
     return (T) table.Rows[index][columnName];
}

但是,您可以使用Field方法来转换dataTable列类型。Field提供对指定行中每个列值的强类型访问。

public static T Field<T>(this DataRow row,  string columnName)

例如,您可以使用此模型:

foreach (var row in dt.AsEnumerable())                        
{
    users.Add(new User(row.Field<int>("Id")) { Name = row.Field<string>("Name") });       
};

微软参考源


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接