未声明为静态时,Web用户控件成员变量不可访问

时间:2012-10-02 06:24:12

标签: c# asp.net static webusercontrol member-variables

我正在使用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被声明为静态。

是否意味着在asp.net页面中加载用户控件时未创建System.Web.UI.UserControl的新对象?这是否意味着当多个客户端(浏览器)尝试播放.wav文件时,在服务器上只创建一个string[] files实例供所有客户端使用?

1 个答案:

答案 0 :(得分:3)

我怀疑问题不在于它根本无法访问。我强烈怀疑问题是你有两个不同的请求,因此有两个不同的WaveFilePlayer实例 - 所以当你执行ButtonPlay_Click时,files变量将为null除非你已经编写了一些代码来在请求之间保留它。

这里的选项是视图状态或某些服务器端会话。您应该使用静态变量,因为这基本上意味着您在所有请求之间共享一个变量(对于所有用户)。