简体   繁体   中英

Extension method return using generics

Is it possible to return a generic type using extension methods ?

For example, I have the following method:

// Convenience method to obtain a field within a row (as a double type) 
public static double GetDouble(this DataRow row, string field) {
    if (row != null && row.Table.Columns.Contains(field))
    {
        object value = row[field];
        if (value != null && value != DBNull.Value)
            return Convert.ToDouble(value);
    }
    return 0;
}

This is currently used as follows:

double value = row.GetDouble("tangible-equity");

but I would like to use the following code:

double value = row.Get<double>("tangible-equity");

Is this possible and if so, what would the method look like?

How about this one:

    public static T Get<T>(this DataRow row, string field) where T: IConvertible 
    {
        if (row != null && row.Table.Columns.Contains(field))
        {
            object value = row[field];
            if (value != null && value != DBNull.Value)
                return (T)Convert.ChangeType(value, typeof(T));
        }
        return default(T);
    }

Convert.ChangeType is much more flexible handling conversions as opposed to just casting. This pretty much reflects your original code, just generic.

It is possible. It could be something like the following:

// Convenience method to obtain a field within a row (as a T type) 
public static T Get<T>(this DataRow row, string field) {
    if (row != null && row.Table.Columns.Contains(field))
    {
        object value = row[field];
        if (value != null && value != DBNull.Value)
            return (T)value;
    }
    return default(T);
}

The DataRow has an extension method called Field that will do very much what you are trying to do. I'm not exactly sure how it will behave with a null value on a double (I know it will handle nullable types). This may not be exactly what you are looking for, but is worth a look.

double value = row.Field<double>("tangible-equity");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM