【发布时间】:2014-01-25 11:50:55
【问题描述】:
我有一组方法,它们以字符串形式接收用户输入,并在每个方法的标题处将其解析为小数、整数等。所以,我在每种方法中都重复了很多次相同的代码,例如:
public ..... CreateOrder(....., string rawSourceAmount)
{
decimal? sourceAmount2 = rawSourceAmount.
TryToDecimal(XUtils.DecimalFormat(2)); // extension method, wrapper of Decimal.TryParse, returns null if fails
if (sourceAmount2 == null)
throw new XBadSourceAmountException(
sourceSystem.Id, rawSourceAmount);
decimal sourceAmount = sourceAmount2.Value;
..........
}
为什么我有sourceAmount2 和sourceAmount?因为后面方法体中我主动使用sourceAmount,不想每次都写sourceAmount.Value。有什么办法可以简化这个模板代码?
所以,任务是:我有string rawSourceAmount。我需要decimal sourceAmount 和一个抛出不同异常的地方。我不需要sourceAmount2。
【问题讨论】:
标签: c# type-conversion tryparse