我发现在我的代码中出现以下错误的频率太高,想知道是否有人知道一些好的策略来避免它。C#:避免由不重写引起的错误ToString
想像这样的一类:
public class Quote
{
public decimal InterestRate { get; set; }
}
在某些时候,我创建使用利率的字符串,像这样:
public string PrintQuote(Quote quote)
{
return "The interest rate is " + quote.InterestRate;
}
现在想象一下,在以后的日子我重构了的InterestRate财产从小数到它自己的类:
public class Quote
{
public InterestRate InterestRate { get; set; }
}
...但说我忘了以覆盖InterestRate类中的ToString方法。除非我仔细查看InterestRate属性的每个用法,否则我可能永远不会注意到它在某个时刻正在转换为字符串。编译器肯定不会选择它。我唯一的救星机会就是通过集成测试。
下一次我打电话给我的PrintQuote方法,我会得到一个字符串是这样的:
“利率是Business.Finance.InterestRate”。
Ouch。这怎么可以避免?
我真的不认为你想让编译器为你构建任意的ToString()实现。 – 2009-06-29 00:58:13