2015-06-30 118 views
4

我想將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?)

的功能似乎簡單,我的眼睛和錯誤消息並不複雜,我只是失去了一些東西讓我的功能工作。

感謝您的幫助,西蒙

+0

什麼是錯誤信息?也許你沒有檢查索引和/或列名是否先存在? – maksymiuk

+0

錯誤在getDBSpecifiedType函數中:「不能隱式地將類型'object'轉換爲'T'。存在明確的轉換(你是否缺少一個轉換?)」 – Slimsim3

回答

2

我最終什麼事利用檢索關於讓更多的答案如下:

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值是否爲em pty並返回null(我使用的是Nullables,因爲與double相比,字符串的默認值是不同的)。如果它不是空的,我可以將它轉換爲泛型類型並返回結果。

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

Microsoft Reference Source