我的项目有以下结构:
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);
}
}编辑:您需要使用我的第二个建议,反射,因为您的变量不是以列表的形式出现的。
https://stackoverflow.com/questions/31278925
复制相似问题