【问题标题】:Converting a DataTable value to a Generic Type将 DataTable 值转换为泛型类型
【发布时间】: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'。存在显式转换(是否缺少强制转换?)”

标签: c# generics datatable


【解决方案1】:

通过搜索关于 SO 的更多答案,我最终使用的是以下内容:

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(例如,我使用 Nullables,因为字符串的默认值与 double 相比是不同的)。如果它不为空,我可以将其转换为泛型类型并返回结果。

【讨论】:

    【解决方案2】:

    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") });       
    };
    

    Microsoft Reference Source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多