调用它时有没有办法在变量名中使用字符串?

时间:2016-09-06 09:13:02

标签: c# visual-studio

我是编程的新手,请原谅我的新手。 我正在使用Visual Studio,在我的程序中,我在“设置”中有一些以月份命名的变量;

JanuaryTotalAmount

JanuarySpentAmount

JanuaryGainedAmount

FebruaryTotalAmount

FebruarySpentAmount

FebruaryGainedAmount

ect...

所以在我的代码中,当我为它们分配值时,我有:

Properties.Settings.Default.JanuaryTotalAmount += EnteredAmount;
Properties.Settings.Default.SpentAmount -= EnteredAmount;

他们只是将输入的值相加以获得总数。

但是我试图让我的代码更整洁,并且想知道是否有办法,根据用户选择它的月份将更改月份名称...

所以

string month = txtBoxMonth.Text;

Properties.Settings.Default."month"TotalAmount += TotalAmount

这将使我不必每个月创建一个巨大的switch语句。 我不知道是否有办法做到这一点,但任何帮助都是值得赞赏的。

4 个答案:

答案 0 :(得分:5)

您提到您当前正在设置文件中存储这些值。

您可以通过键访问您的设置:

public void GetMonthAmount(string month)
{
    string keyName = month + "TotalAmount";
    object monthData = Properties.Settings.Default[keyName];
}

答案 1 :(得分:3)

正如其他人所建议的那样,您可以使用Dictionary<>来存储这些值,并将键定义为您也定义的enum。但是,您不能直接拥有此类型的设置值,因此您必须将其包装在类中:

public enum Month
{
    January,
    February,
    // and so on...
    December
}


public class Amounts
{
    public Amounts()
    {
        Months = new Dictionary<Month, int>();
    }

    public Dictionary<Month, int> Months { get; set; }
}

然后,您可以为每个花费获得金额的设置添加值,并按以下方式访问它们:

Properties.Settings.Default.TotalAmounts = new Amounts();

Properties.Settings.Default.TotalAmounts.Months[Month.February] = 5;

答案 2 :(得分:0)

感谢大家的帮助,所以这是我能够用提供的答案弄清楚的。是的,我正在用代表金额的小数来徘徊。

string key = month + "TotalAmount"; 
decimal tempDec = Convert.ToDecimal(Properties.Setting.Default[key]); // Creates a decimal to store the setting variable in using the key to access the correct setting variable
tempDec += Convert.ToDecimal("EnteredAmount"); // Adds the value of the Setting variable to the amount entered. 
Properties.Settings.Default[key] = tempDec; // Then sets the Setting variable to equal the temp variable.
Properties.Setting.Default.Save();

效果很好,节省了很多空间!

答案 3 :(得分:-1)

一种选择是尝试使用Reflection。使用反射,您可以使用SetValueGetValue函数按名称设置/获取属性值 您是新手,因此您需要详细阅读,以便发布一些链接以供参考。
http://www.tutorialspoint.com/csharp/csharp_reflection.htm
http://www.dotnetperls.com/reflection-property
https://msdn.microsoft.com/en-us/library/axt1ctd9(v=vs.110).aspx

C#代码示例(obj是具有属性的对象):

Type type = obj.GetType();
System.Reflection.PropertyInfo propertyInfo = type.GetProperty("JanuaryTotalAmount ");
propertyInfo.SetValue(obj, valueToSet, null);

所以现在根据需要创建逻辑。

相关问题