是否有一种方法可以在调用变量时使用'

本文关键字:变量 调用 方法 一种 是否 | 更新日期: 2023-09-27 18:05:53

我是编程新手,所以请原谅我的新手。我正在使用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语句。我不知道是否有办法做到这一点,但任何帮助都是非常感谢的。

是否有一种方法可以在调用变量时使用'

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

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

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

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

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;

感谢大家的帮助,所以这是我能够通过提供的答案弄清楚的。是的,我正在处理代表金钱数量的小数。

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();

它工作得很好,节省了很多空间!

一个选择是尝试使用反射。使用反射,您可以使用SetValue和GetValue函数按名称设置/获取属性值。
你是新的,所以你需要阅读更多的细节,所以张贴一些链接供参考。
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);

现在根据你的需要创建逻辑