我正在使用 C# 创建一个 Web 用户控件来播放服务器中的一些 .wav 文件。以下是我的代码。
public partial class WaveFilePlayer : System.Web.UI.UserControl
{
//private string[] files;
private static string[] files;
protected void ButtonLoad_Click(object sender, EventArgs e)
{
string resourcePath = ConfigurationManager.AppSettings["ResourcePath"];
string searchPattern = ConfigurationManager.AppSettings["SearchPattern"];
files = System.IO.Directory.GetFiles(path, searchPattern);
}
protected void ButtonPlay_Click(object sender, EventArgs e)
{
int selectedIndex = ListBoxFiles.SelectedIndex;
SoundPlayer soundPlayer = new SoundPlayer(files[selectedIndex]);
soundPlayer.Play();
}
如上面的代码所示,我声明string[] files
为成员变量。然后我在ButtonLoad_Click
方法中分配它。但是NullReferenceException
当我尝试在ButtonPlay_Click
方法中访问它时它会抛出一个,除非string[] files
被声明为静态的。
这是否意味着System.Web.UI.UserControl
在 asp.net 页面中加载用户控件时未创建新对象?这是否意味着当多个客户端(浏览器)尝试播放 .wav 文件时,string[] files
在服务器上只创建一个实例供所有客户端使用?