如何从其他方法访问已在Windows窗体加载方法中声明的对象? [英] How to access objects which have been declared in a Windows Form Load Method from other methods?
问题描述
我正在创建一个Windows窗体应用程序,我在表单Load方法中创建了大量对象。这些对象具有通过其构造函数链接到它们的Audio和PictureBox,并且有一个方法来播放声音文件。
我想要做的是在Windows窗体上通过图像的单击事件启动PlaySound方法。但是我在从类中的其他地方访问对象时遇到问题。我在下面添加了一些代码以使其更清晰:
表单加载方法(声明所有这些对象):
< pre lang =c#> public void Form_Load( object sender,EventArgs e)
{
Indicator Indicator1 = new 指标(IndicatorImage1,( new
Audio( Properties.Resources.Sound1.wav) ));
// ....还有更多这些
}
指标类:
<前lang =c#> 类指标
{
PictureBox图片;
音频声音;
public 指标(PictureBox ImageIn,Audio NoteIn)
{
image = ImageIn;
Sound = NoteIn;
}
public void ShowSoundImage()
{
image.Show();
}
public void PlaySound()
{
Sound.Play();
}
单击我想要使用对象及其方法的事件(这是在主窗体类中):
private void IndicatorImage1_Click(对象发件人,EventArgs e)
{
// 这是我试图实现失败
Indicator1.PlaySound();
}
我目前收到的错误如下:
当前上下文中不存在名称Indicator1
有没有办法以不同的方法访问对象方法到Windows窗体中创建的方法?或者是否有更合理的方式来组织这些代码?
非常感谢
将其声明为 Form
类的成员,而不是特定方法的本地成员。请参阅 .NET Book Zero [ ^ ]和 C#语言规范 [ ^ ]。
I am creating a Windows Forms application where I'm creating a large number of objects in the forms Load method. These objects have Audio and PictureBoxs linked to them through their constructors and a method is in place to play the sound file.
What I am trying to do is have the "PlaySound" method started by a click event of an image on the Windows Form. However I am having problems accessing the objects from elsewhere in the class. I have included some code below to make it a little clearer:
Form Load Method (where all these objects are declared):
public void Form_Load(object sender, EventArgs e)
{
Indicator Indicator1 = new Indicator(IndicatorImage1, (new
Audio("Properties.Resources.Sound1.wav")));
//....Theres many more of these
}
Indicator Class:
class Indicator
{
PictureBox image;
Audio Sound;
public Indicator(PictureBox ImageIn, Audio NoteIn)
{
image = ImageIn;
Sound = NoteIn;
}
public void ShowSoundImage()
{
image.Show();
}
public void PlaySound()
{
Sound.Play();
}
Click Event where I want to make use of the object and its methods (This is within the main form class):
private void IndicatorImage1_Click(object sender, EventArgs e)
{
//This is the line I am trying to implement unsuccessfully
Indicator1.PlaySound();
}
I am currently getting an error as follows:
"The Name 'Indicator1' does not exist in the current context"
Is there a way to access the objects methods in a different method to where it was created within a windows form? Or is there a more logical way of organising this code?
Many Thanks
Declare it as a member of the Form
class, rather than local to a particular method. See .NET Book Zero[^] and The C# Language Specification[^].
这篇关于如何从其他方法访问已在Windows窗体加载方法中声明的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!