在参数中使用字符串

本文关键字:字符串 参数 | 更新日期: 2023-09-27 18:03:20

这是一个新手的问题,但我试图使用字符串(myButton),这是根据调用该方法的按钮设置的,并试图在参数内使用该字符串,但我的IDE认为我直接使用字符串。下面是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GMA
{
     public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
            string myButton;//Currently selected button
            private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form
            {
                myButton = "button1";
                SoundRoute();
            }
            public void SoundRoute()
            {
                if ((myButton).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc.
                {
                SoundCall subForm = new SoundCall();
                subForm.Show();
                }
            }
    }
}

我很感激任何帮助。我知道我可以为每个按钮做一个新的,但这既是为了学习目的,也是为了实用。

在参数中使用字符串

使用sender参数并将其传递给SoundRoute方法。这就是它的作用:

public void SoundRoute(object sender)
{
    if (((Button)sender).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc.
    {
        SoundCall subForm = new SoundCall();
        subForm.Show();
    }
}

那么你的事件变成:

 private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form
 {
     SoundRoute(sender);
 }

然后,你可以有一个单一的事件,所有按钮都连接到(因为它"将复制到表单上的所有按钮")。