我有以下簡單功能:指定類型的通用功能
private static Nullable<T> CastValue<T>(object val)
where T : struct
{
if (!(val is DBNull))
{
return (T) val;
}
return null;
}
我想叫它在遍歷這樣行/數據表中的列:
var table = CreateTable();
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Type type = column.DataType;
CastValue<type>(row[column]);
}
}
然而,我得到以下錯誤:
The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?)
是否有一種方法來調用一個泛型函數與泛型參數在運行時間確定?
Uppercase T dude .. on this:'CastValue(row [column]);'。這是你的「類型」無法找到錯誤的原因。至於你的主要問題..我認爲'動態'可能對你有幫助。 –
@SimonWhitehead - 'type'是一個'Type'實例,而不是'Type'類。因爲'Type'不是struct,所以不會編譯。 – Lee
@Lee True,但正如我所說..這是他發佈的錯誤的原因:) –