简体   繁体   English

使用泛型返回扩展方法

[英]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. Convert.ChangeType处理转换要灵活得多,而不仅仅是强制转换。 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. DataRow 有一个名为Field的扩展方法,它可以做很多你想做的事情。 I'm not exactly sure how it will behave with a null value on a double (I know it will handle nullable types).我不确定它会如何处理 double 上的空值(我知道它会处理可空类型)。 This may not be exactly what you are looking for, but is worth a look.这可能不是您正在寻找的内容,但值得一看。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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