[英]How do I call a method from another class within a listbox?
In my listbox form I want to make it possible to call a method from a class in a different folder. 在我的列表框形式中,我希望可以从其他文件夹中的类调用方法。 Here is what I thought I was meant to do:
这是我原本打算做的事情:
public void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
SharedClasses.Form.FormConsole newFormConsole =
new SharedClasses.Form.newFormConsole();
}
You are creating a new instance of the FormConsole
class, which I'm guessing is probably not what you wanted to do. 您正在创建
FormConsole
类的新实例,我想这可能不是您想要的。
What you probably want to do is have the form that contains your ListBox have a reference to an existing instance of FormConsole
. 你可能想要做的就是拥有一个包含列表框必须的现有实例的引用形式
FormConsole
。 Then you can call methods on that instance. 然后,您可以在该实例上调用方法。
So, somewhere in the class that contains your ListBox: 因此,在包含您的ListBox的类中的某个位置:
private FormConsole _myForm;
You can set that in the constructor for your class, or provide a getter and setter: 您可以在类的构造函数中进行设置,也可以提供getter和setter:
public FormConsole MyForm
{
get { return _myForm; }
set { _myForm = value; }
}
// and/or...
public ListBoxForm(FormConsole myForm)
{
MyForm = myForm;
}
Then you can call (public) methods on myForm: 然后,您可以在myForm上调用(公共)方法:
public void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
MyForm.MyMethod();
}
The simplest i think would be to copy the other application folder in the main folder of your current application and then using the classes from the other application folder with this code snippet: 我认为最简单的方法是将另一个应用程序文件夹复制到当前应用程序的主文件夹中,然后将另一个应用程序文件夹中的类与以下代码段一起使用:
using yourcurrentappname.otherappsfoldername;
and now you can easily access the methods of other app's classes here in the current app. 现在您可以在当前应用程序中轻松地访问其他应用程序类的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.