使用泛型的扩展方法返回
例如,我有以下方法:
// 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;
}
目前使用如下:
double value = row.GetDouble("tangible-equity");
但我想使用以下代码:
double value = row.Get<double>("tangible-equity");
这可能吗?如果可以,该方法会是什么样子?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个怎么样:
Convert.ChangeType与仅仅转换相比, 处理转换要灵活得多。这几乎反映了您的原始代码,只是通用的。
How about this one:
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:
DataRow 有一个名为 Field 这将非常适合您正在尝试做的事情。我不太确定它将如何处理双精度值上的空值(我知道它将处理可为空类型)。这可能不完全是您正在寻找的内容,但值得一看。
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.