简体   繁体   中英

Classes using other classes/methods

I made a program that essentially contained 150 actions, all in the first form. It has become a nightmare to manage and a friend recommended splitting groups of actions into separate classes.
Ideally going from: Do {1,2,3,4,5} to Do {A,B} where A is {1,2,3} and B is {4,5} .

To practice, I decided to try to work 2 classes:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    public void button_Click(object sender, RoutedEventArgs e)
    {
        if (checkBox1.IsChecked == true)
        {
            checkTrue();
        }
        else
        {
            checkFalse();
        }
    }

    public void checkTrue()
    {
        textBox.Text = "checkbox was checked";
    }

    public void checkFalse()
    {
        textBox.Text = "unchecked :(";
    }
}

How would I go about changing this to a set it as a new class to be called upon? When creating a new class "checkBool", I wrote the following in a new .cs:

class checkBool
{
    public void checkTrue()
    {
        textBox.Text = "checkbox was checked";
    }

    public void checkFalse()
    {
        textBox.Text = "unchecked :(";
    }
}

However, the textbox is no longer recognized. How can I make this new class understand the reference?

The textbox is not recognized by the checkbool instance because it doesn't know about it.

One quick way to "let it know about it" is passing the textbox as a parameter to the checkTrue() and checkFalse() operations, like this:

class checkBool
{
    public void checkTrue(TextBox textBox)
    {
        textBox.Text = "checkbox was checked";
    }
    public void checkFalse(TextBox textbox)
    {
        textBox.Text = "unchecked :(";
    }
}

So the button click handler would be:

public void button_Click(object sender, RoutedEventArgs e)
{
    checkBool cb = new checkBool();
    if (checkBox1.IsChecked == true)
    {
        cb.checkTrue(textbox);
    }
    else
    {
        cb.checkFalse(textbox);
    }
}

Keep in mind that by doing this you are introducing a dependency to your class checkBool (It depends to TextBox now).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM