【发布时间】:2017-09-20 13:41:59
【问题描述】:
我有一组 const,然后我动态创建一个变量,该变量等于其中一个 const 名称。我需要调用那个 const,我知道我可以使用 if else 语句,但我想知道是否有更好的方法谢谢!
public const int LifeBand1Standard = 78;
public const int LifeBand1Multi = 61;
public const int LifeBand2Standard = 71;
public const int LifeBand2Multi = 56;
public const int LifeBand3Standard = 62;
public const int LifeBand3Multi = 48;
public const int LifeBand4Standard = 56;
public const int LifeBand4Multi = 44;
public const int LifeBand5Standard = 45;
public const int LifeBand5Multi = 35;
// Band discounts/loads for trauma cover
public const int TraumaBand1Standard = 140;
public const int TraumaBand1Multi = 126;
public const int TraumaBand2Standard = 135;
public const int TraumaBand2Multi = 121;
public const int TraumaBand3Standard = 121;
public const int TraumaBand3Multi = 109;
public const int TraumaBand4Standard = 110;
public const int TraumaBand4Multi = 99;
public const int TraumaBand5Standard = 100;
public const int TraumaBand5Multi = 90;
protected float GetPercentageFromBand(int band)
{
var constantName = "Life";
if (IsTraumaCover == true)
{
constantName = "Trauma";
}
constantName += "Band" + band;
if (IsMultiLife == true)
{
constantName += "Multi";
}
else
{
constantName += "Standard";
}
// Constant should look something like LifeBand3Standard and will return the value of the const LifeBand3Standard
BandPercentage = InsuranceBandFetcher.constantName;
}
【问题讨论】:
-
不,您不能以这种方式访问变量
-
改用
Dictionary -
@L.B 我对 c# 很陌生,我如何使用字典来做到这一点?
-
为什么不创建一个枚举和其他人所说的使用字典
-
如果需要保留
const的设计,可以使用反射:typeof(InsuranceBandFetcher).GetField(constantName).GetRawConstantValue();