Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

windows forms designer - C# Adressing multiple variables using a for()

I have this code:

cpMythic0.Text = Properties.Settings.Default.M0;

and let's say I have 31 cpMythic (string) variables all being named "cpMythic0, cpMythic1, cpMythic2 ... cpMythic30 and the same goes with some Properties Settings string variables called "M0,M1,M2...M30"

Instead of writing this:

cpMythic0.Text = Properties.Settings.Default.M0;
cpMythic1.Text = Properties.Settings.Default.M1;

I would like to use a for() function, with an i variable but I don't really know the syntax. I would appreciate any help.

question from:https://stackoverflow.com/questions/65853922/c-sharp-adressing-multiple-variables-using-a-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure why you'd want to do this, but this is achievable using reflection.

Here is an example:

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Fill_Click(object sender, EventArgs e)
        {
            string propertyMatcher = "cpMythic";

            var defaultSettings = new Properties.Settings.Default(); //Get instance of default settings
            var settingProperties = defaultSettings.GetType().GetFields(); //Get default setting properties.

            foreach (TextBox control in this.Controls.OfType<TextBox>().Where(c => c.Name.StartsWith("cpMythic"))) //Loop through controls, and filter
            {
                string settingPropertyName = "M" + control.Name.Substring(propertyMatcher.Length);

                var settingProperty = settingProperties.FirstOrDefault(p => p.Name == settingPropertyName);

                var value = settingProperty.GetValue(defaultSettings); //Get the value of the corresponding setting using reflection

                control.Text = value.ToString(); //Set value
            }
        }

        private static class Properties
        {

            public static class Settings
            {

                public class Default
                {
                    public string M0 = "Default Value 0";
                    public string M1 = "Default Value 1";
                    public string M2 = "Default Value 2";
                }
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...