0

当我声明一个变量时,可以说

public string [] companiesArray = {"Google","BBC","CNN","SportsDirect","Microsoft"};

就在公共部分类 Default : System.Web.UI.Page 之后,该变量是可访问的,但是当我在 Page_Load 方法中声明该变量时,该变量是不可访问的。

public void Page_Load(object sender, EventArgs e)
    {
    string [] companiesArray = {"Google","BBC","CNN","SportsDirect","Microsoft"};
    }

可能是什么问题呢?有人可以帮帮我吗?

4

3 回答 3

4

Read up on Scope

If a variable is defined within your Page_Load method, then it is local to that method

If you defined it outside of the method, it's visible to the rest of the code, and is typically refered to as a Field, e.g.

public partial class Page : System.Web.UI.Page
{
   private string[] companiesArray = {"Google","BBC","CNN","SportsDirect","Microsoft"};
   public void Page_Load(object sender, EventArgs e)
   {
      //companiesArray  is visible here
   }

   public void SomeOtherMethod()
   {
      //companiesArray is visible here too
   }
}
于 2013-06-20T12:11:48.930 回答
3

如果您在其中声明变量,则Page_load它是该范围的局部变量。

如果您在之后声明变量public partial class Default : System.Web.UI.Page

它是所有页面的全局变量。

于 2013-06-20T12:08:01.797 回答
3

您需要了解范围。

在页面中定义数组时,您将范围定义为类。您可以在类中的任何位置使用该变量。

public partial class Default : System.Web.UI.Page
{
   string[] companiesArray;

    public void DoFizz()
    {
        companiesArray[0] = "Fizz";
    }

    public void DoBuzz()
    {
        companiesArray[1] = "Buzz";
    }
}

When you define it in page load, then the scope is limited to that method, so you can only use it within that method.

public partial class Default : System.Web.UI.Page
{
    public void Page_Load(object sender, EventArgs e)
    {
        string[] companiesArray;
    }
}

One of the major advantages of this, is if you declare variables within methods, it stops you accidentaly using a variable that may have been defined and used elsewhere. If this were not the case you wouldn't be able to guarantee the state of your variable.

于 2013-06-20T12:09:57.453 回答