Как получить доступ к textBox1 в классе WinForms C#

Рейтинг: 0Ответов: 1Опубликовано: 04.04.2023

Form1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "****Fun With Class Types****" + "\r\n";
            Car myCar = new Car();
            myCar.petName = "Henry";
            myCar.currSpeed = 10;

            for (int i = 0; 1 <= 10; i++)
            {
                myCar.SpeedUp(5);
                myCar.PrintState();
            }
        }
    }
}

Class Car

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lab_Work_1
{
    
    class Car    
    {
        
        public string petName;
        public int currSpeed;


        public void PrintState()
        {
            textBox1.Text += Convert.ToString("{0} is going {1}MPH. " + petName + currSpeed + "\r\n");
        }
      
        public void SpeedUp(int delta)
        {
            currSpeed += delta;
        }
    }
}

Ответы

▲ 1Принят

Как это выглядит у вас вкратце:

myCar.PrintState();

...

    class Car    
    {
        ...

        public void PrintState()
        {
            textBox1.Text += Convert.ToString("{0} is going {1}MPH. " + petName + currSpeed + "\r\n");
        }
    }

Лучше работать с интерфейсом только в основном классе, а от Car просить текстовое представление информации:

textBox1.Text += $"{myCar.GetState()}\r\n";

...

    class Car    
    {
        ...

        public string GetState()
        {
            return $"{petName} is going {currSpeed}MPH.";
        }
    }

Если я правильно вспомнил, как $-строками в C# пользоваться.