【发布时间】:2010-04-04 14:14:44
【问题描述】:
我有一个业务类,其中包含用于各种证券交易所价格类型的许多属性。这是该类的一个示例:
public class Prices
{
public decimal Today {get; set;}
public decimal OneDay {get; set;}
public decimal SixDay {get; set;}
public decimal TenDay {get; set;}
public decimal TwelveDay {get; set;}
public decimal OneDayAdjusted {get; set;}
public decimal SixDayAdjusted {get; set;}
public decimal TenDayAdjusted {get; set;}
public decimal OneHundredDayAdjusted {get; set;}
}
我有一个旧系统,它使用字符串 ID 来提供价格以识别价格类型。
例如
Today = "0D"
OneDay = "1D"
SixDay = "6D"
//..., etc.
首先,我将所有值加载到 IDictionary() 集合中,因此我们有:
[键] 值
[0D] => 1.23456
[1D] => 1.23456
[6D] => 1.23456
......等等。
其次,我使用将上述集合作为参数的方法设置价格类的属性,如下所示:
SetPricesValues(IDictionary<string, decimal> pricesDictionary)
{
// TODAY'S PRICE
string TODAY = "D0";
if (true == pricesDictionary.ContainsKey(TODAY))
{
this.Today = pricesDictionary[TODAY];
}
// OneDay PRICE
string ONE_DAY = "D1";
if (true == pricesDictionary.ContainsKey(ONE_DAY))
{
this.OneDay = pricesDictionary[ONE_DAY];
}
//..., ..., etc., for each other property
}
有没有更优雅的技术来设置大量属性? 谢谢, j
【问题讨论】:
-
请不要写
if (true == something_or_other)。true ==完全是多余的,很伤人的眼睛。 -
有些人可能认为它更清楚。虽然我同意你的观点,但它不会伤害我的眼睛(我见过更糟糕的代码,配得上“伤害”这个标题);-)
-
@Abel:按照你的逻辑,(true == (true == foo)) 不是更清楚吗?您也可以无限地继续它以获得无限清晰!
-
哈哈,我自己并没有认为它更清楚,但有些人认为它更清楚(为什么不
!false == ContainsKey())。同样的方式,他们可以使用== false而不是!或else。但是代码中有更明显的地方需要注意,这就是为什么 Guazz 提出了这个问题,我猜 :)
标签: c# coding-style properties