您需要了解范围。
在页面中定义数组时,您将范围定义为类。您可以在类中的任何位置使用该变量。
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.