【发布时间】:2012-05-13 19:19:31
【问题描述】:
在我的一个项目中,我使用了以下两种方法。 1. GetDoubleValue 和 2. GetIntValue。 GetDoubleValue 使用 double.TryParse 参数 str 字符串,如果失败则返回 0,而 GetIntValue 尝试 int.TryParse 参数 str 字符串,如果失败则返回 0。我想要的是将这两种方法组合成一个通用方法,该方法与字符串 str 一起接收参数 T ,这样如果我想使用 GetDoubleValue 方法,我可以使用 double 作为参数 T ,如果我想使用 GetIntValue 方法,我可以使用参数 T 的 int
public double GetDoubleValue(string str)
{
double d;
double.TryParse(str, out d);
return d;
}
public int GetIntValue(string str)
{
int i;
int.TryParse(str, out i);
return i;
}
注意:我已经尝试过这样的事情;
private T GetDoubleOrIntValue<T>(string str) where T : struct
{
T t;
t.TryParse(str, out t);
return t;
}
编辑
在我的数据库中,我在具有数字数据类型的不同表中有 30 多个列。如果用户没有在文本框中输入任何内容,即他将所有或部分文本框留空,我想在每列中插入 0。如果我不使用 GetIntValue 方法,我将不得不使用方法体超过 30 次。这就是为什么我通过方法方法来做到这一点。例如,我正在写三十多个示例中的三个
cmd.Parameters.Add("@AddmissionFee", SqlDbType.Decimal).Value = GetIntValue(tbadmissionfee.Text);
cmd.Parameters.Add("@ComputerFee", SqlDbType.Decimal).Value = GetIntValue(tbcomputerfee.Text);
cmd.Parameters.Add("@NotesCharges", SqlDbType.Decimal).Value = GetDoubleValue(tbnotescharges.Text);
我想将上述两种方法结合起来,因为今天我有两种这样的方法,如果结合起来不会给编程带来任何更好的改进,但明天我可能会有数十种这样的方法,它们会更好地组合成一个通用方法。例如,我可能有 GetInt32Value、GetShortValue 等。希望现在清楚我为什么要这个???
【问题讨论】:
-
使用当前的泛型类型约束,这是不可能的。
-
你打算怎么称呼这个泛型方法?
-
您确定要在解析失败时让此函数静默返回默认值吗?
-
我写了一个generic parser helper。寻找带有反射的
TryParse方法,并缓存委托以获得高性能。 -
我用谷歌找到了一篇相关文章:geekswithblogs.net/michelotti/archive/2008/10/05/…