c# - 我可以在 windows form1.cs 中创建一个对象,然后我可以在多个单击事件中使用该对象和对象内容(C#)
问题描述
我可以在其中创建一个对象,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?
}
}
解决方案
您应该创建一个新文件并在其中创建一个新类。你要找的是一个字段。字段是属于类实例的变量。
这是一个示例:( 在您的代码中添加了一些额外的内容)
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}");
}
}
}
}
推荐阅读
- ionic-framework - 未检测到匹配的服务人员。您可能需要重新加载页面
- java - S3 文件作为 PDFBox 的输入
- javascript - 正则表达式计算文本缩进中空格和制表符的数量
- c# - 如何在 Visual Studio 中为 Excel 创建 GUI 插件?
- android - Recyclerview 滚动到 NestedScrollView 内的特定位置
- javascript - 如何将数组附加到对象中
- javascript - 我已经下载了一个文本文件。我不想下载,而是想使用 javascript 在 html 页面中显示它
- apache-kafka - 在 Ubuntu 19.10 上安装 librdkafka
- flutter - 如何在下拉颤动中设置初始默认值
- hibernate - Spring JPA:保存与作为主表的实体关联的实体