-4

文字列変数に格納されている C# ステートメントを実行したいと考えています。例えば:

string statement1 = "button1.Visible = true";
string statement2 = "button1.Text = \"Number\"";
4

3 に答える 3

2

Looking at your comments and that you have 80 controls requiring very similar action, dynamic compilation may be an overkill for this purpose. You can use use Controls collection of the parent container along with the Tag property of your buttons to achieve it. A single event handler would suffice.

You can use LINQ members like OfType and Cast to make your code even smaller.

Edit

After looking at your latest comment, what you should do is to programmatically create your buttons and add them to your Form or whatever container you have. You can then keep a Dictionary<string, Button> that will let you either iterate over the collection, or access an individual button through its name. Something like:

//Declare this globally
Dictionary<string, Button> Dic = new Dictionary<string, Button>(81);

//put this in the constructor
for(int i=0; i<81; i++)
{
    Button b = new Button();
    b.Text = i; //or Random or whatever
    b.Name = "btn" + i.ToString();
    this.Controls.Add(b);
    Dic.Add(b.Name, b);
}

Later you can do both iteration like this:

foreach(var item in Dic)
{
    item.Value.Visible = true; //or false
}

and key-based access like this:

Dic["btn45"].Visible = true; //or false

Since you're creating Sudoku, i probably think you should use TableLayoutPanel with appropriate number of rows and columns at design-time and then add your buttons to the panel and set their Row/Column property in the loop. This will help better respond to resizing events etc.

于 2013-09-30T06:11:29.993 に答える
1

デリゲートの使用についてはどうですか?

Action statement1 = () => button1.Visible = true;
Action statement2 = () => button1.Text = "Number";
于 2013-09-30T14:22:43.433 に答える