问题
I use a extension method to check a DataRowField for null
public static string GetValue(this System.Data.DataRow Row, string Column)
{
if (Row[Column] == DBNull.Value)
{
return null;
}
else
{
return Row[Column].ToString();
}
}
Now I wonder if i could make this more generic. In my case the return type is always string but the Column could also be Int32 or DateTime
Something like
public static T GetValue<T>(this System.Data.DataRow Row, string Column, type Type)
回答1:
public static T value<T>(this DataRow row, string columnName, T defaultValue = default(T))
=> row[columnName] is T t ? t : defaultValue;
or for earlier C# versions:
public static T value<T>(this DataRow row, string columnName, T defaultValue = default(T))
{
object o = row[columnName];
if (o is T) return (T)o;
return defaultValue;
}
and sample uses (the underlying type has to match exactly as there is no conversion):
int i0 = dr.value<int>("col"); // i0 = 0 if the underlying type is not int
int i1 = dr.value("col", -1); // i1 = -1 if the underlying type is not int
Other alternatives without extension can be nullable types:
string s = dr["col"] as string; // s = null if the underlying type is not string
int? i = dr["col"] as int?; // i = null if the underlying type is not int
int i1 = dr["col"] as int? ?? -1; // i = -1 if the underlying type is not int
The column name lookup is slower if the case doesn't match, because a faster case sensitive lookup is attempted first before the slower case insensitive search.
回答2:
Signature of your method will be as follows
public static T GetValue<T>(this System.Data.DataRow Row, string Column)
In Else part just change the following
return (T)Row[Column];
来源:https://stackoverflow.com/questions/39723298/generic-datarow-extension