我的项目有以下结构:
public struct Money
{
public CurrencyCodes Currency;
public decimal Amount;
}
public class Foo
{
public Money AdultFare { get; set; }
public Money ChildFare { get; set; }
public Money BabyFare { get; set; }
public Money AdultFee { get; set; }
public Money ChildFee { get; set; }
public Money BabyFee { get; set; }
public Money TotalFare { get; set; }
public Money TotalFee { get; set; }
}现在,我需要将所有Foo货币字段从一种货币转换为另一种货币。什么是最好的解决方案设计?用反射?另一个主意?
发布于 2015-07-07 20:58:04
我建议将所有这些V字段变成一个数组,如下所示:
public class Foo
{
public Money[] V { get; set; } // instantiate as "new Money[10]"
}然后,您可以遍历V数组并轻松地转换每个数组,如下所示:
// in class Foo
public void ConvertAllMoney(CurrencyCodes newCurrency)
{
foreach (Money m in V)
m = m.ConvertTo(newCurrency);
}或者,如果您不想创建一个数组,您实际上可以使用反射,正如您建议的那样:
// in class Foo
public void ConvertAllMoney(CurrencyCodes newCurrency)
{
foreach (var p in typeof(Foo).GetProperties().Where(prop => prop.PropertyType == typeof(Money)))
{
Money m = (Money)p.GetValue(this, null);
p.SetValue(this, m.ConvertTo(newCurrency), null);
}
}编辑:您需要使用我的第二个建议,反射,因为您的变量不是以列表的形式出现的。
发布于 2015-07-07 20:50:33
与V1不同,V2.V10创建了一个列表:
List<Money> V = new List<Money>();
V.Add (new Money()); //repeat 10 times然后您可以迭代:
foreach (Money m in V)
{
//Do your conversion
}编辑后的建议
List<Money> AllMoneyFields = new List<Money>();
public Foo()
{
AllMoneyFields = new List<Money>
{AdultFare,ChildFare,BabyFare,AdultFee,ChildFee,BabyFee,TotalFare,TotalFee};
}然后,在另一个“转换”方法中,您可以遍历AllMoneyFields。
建议3
如果要保护未来的Money属性,请使用enum来描述该属性:
//Add a field to Money: public MoneyDescription Description;
enum MoneyDescription
{
AdultFare,
AdultFee,
....
TotalFee
}
List<Money> V = new List<Money>();
foreach (MoneyDescription md in Enum.GetValues(typeof(MoneyDescription)))
{
V.Add(new Money() {Description = md});
}https://stackoverflow.com/questions/31278925
复制相似问题