Is there a way to use a string in a variable name when called?

I am new to programming, so excuse my novelty. I use Visual Studio, and in my program I have some variables in the settings, which are called months;

JanuaryTotalAmount

JanuarySpentAmount

JanuaryGainedAmount

FebruaryTotalAmount

FebruarySpentAmount

FebruaryGainedAmount

ect...

So, in my code, when I assign them to values, I:

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

They simply add the values ​​that are entered to get the total.

But I tried to keep my code tidier and wondered if there is a way based on the fact that the user selects it, this will change the name of the month ...

So,

string month = txtBoxMonth.Text;

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

This will not allow me to create a giant switch statement for each month. I don't know if there is a way to do this or not, but any help would be appreciated.

+4
source share
4

, .

:

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

, 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;
+3

, . , , .

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

!

0

- . , / , 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

# (obj - ):

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

, .

-1

Source: https://habr.com/ru/post/1653768/


All Articles