Могу ли я создать объект в windows form1.cs, чтобы затем использовать объект и содержимое объектов в нескольких событиях щелчка (C#) - PullRequest
0 голосов
/ 22 марта 2020

Могу ли я создать объект в windows form1.cs, чтобы я мог затем использовать его и содержимое объекта в нескольких событиях щелчка в файле windows form1.cs?

Это код, который демонстрирует мое намерение:

namespace example
{ 
    public partial class Form1 : Form 
    {

        // here i want to call a class an make an objekt thats contains list of "books" from other 
        // classes 
        // (classname variable = new classname)


        public Form1()
        {
            InitializeComponent();            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           // here I want to use the object made from the code above.
           // variable.function() 
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {
           // here I want to use the object made from the code above.
           // variable.function()
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

       // is there anyway to do this or is it another place that makes the object reachable from the 
       // places I want to call it?

    }
}

Ответы [ 2 ]

1 голос
/ 22 марта 2020

Вы должны создать новый файл и создать в нем новый класс. То, что вы ищете, это поле. Поле - это переменная, которая принадлежит экземпляру класса.

Вот пример: (добавлено немного дополнительного в ваш код)

namespace exemple   // <--- I know this is spelled wrong, but I'm using the original code, I'm not a spelling checker ;-)
{
    public partial class Form1 : Form
    {
        // the declaration of the field (you can instantiate it here as well) 
        private BookCase _bookCase;

        public Form1()
        {
            InitializeComponent();     

            // create an instance of the bookcase and store in into a field.       
            _bookCase = new BookCase();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            // add some books.
            _bookCase.Add(new Book { Title = "Something", Author = "John" };
            _bookCase.Add(new Book { Title = "Anything", Author = "Doe" };
            // variable.function()**

        }

        private void tabPage1_Click(object sender, EventArgs e)
        {
            // call a method of the bookcase
            _bookCase.ShowBooks();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

       /**/ is there anyway to do this or is it another place thats make the objekt reachable from the 
       // places i whant to call it?**

    }
}

namespace exemple
{
    // just a book class
    public class Book
    {
        // with some properties
        public string Title {get;set;}
        public string Author {get;set;}
    }
}

namespace exemple
{
    // a bookcase which contains a list of books store in a field
    public class BookCase
    {
        private List<Book> _books = new List<Book>();

        public void Add(Book book)
        {
            // add a book
            _books.Add(book);
        }

        public void ShowBooks()
        {
            // show all books
            foreach(var book in _books)
            {
                MessageBox.Show($"Title: {book.Title}");
            }
        }
    }
}
0 голосов
/ 22 марта 2020

Я думаю, вы хотите следующее:

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

            textBox1.TextChanged +=  new EventHandler(textBox_TextChanged);
            textBox2.TextChanged += new EventHandler(textBox_TextChanged);
            textBox3.TextChanged += new EventHandler(textBox_TextChanged);
        }

        private void textBox_TextChanged(object sender, EventArgs e)
        {
            TextBox box = sender as TextBox;
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...