访问其范围之外的变量值
我需要访问另一个函数中的变量。要访问的变量和访问函数是相同的类,相同的项目但功能不同。此外,没有全局变量声明访问其范围之外的变量值
protected void gdDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
int dbCompany = Convert.ToInt32(gdDisplay.SelectedRow.Cells[2].Text);
}
void gvFunction_Update()
{
//place to access dbcompany variable//
}
您无法访问,因为dbCompany
是gdDisplay_SelectedIndexChanged
方法的局部变量。你将不得不宣布在类级别的全局变量来代替: -
public partial class Default : System.Web.UI.Page
{
int dbCompany = 0;
protected void Page_Load(object sender, EventArgs e)
{
//Page Load event
}
protected void gdDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
dbCompany = Convert.ToInt32(gdDisplay.SelectedRow.Cells[2].Text);
}
void gvFunction_Update()
{
int x = dbCompany ;
}
}
如何修改函数签名为void'void gvFunction_Update(int something)'并将dbCompany作为参数传递? –
@GianPaolo - 这取决于要求,如果OP想从'gdDisplay_SelectedIndexChanged'调用该方法,那么它很好,但OP从未提及过这一点。 –
在类中创建一个私有财产“DbCompany”通过属性
private int DbCompany {get;set;}
protected void gdDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
int dbCompany = Convert.ToInt32(gdDisplay.SelectedRow.Cells[2].Text);
//This is where the property gets its value
DbCompany = dbCompany;
}
void gvFunction_Update()
{
//place to access dbcompany variable//
//Get the value from DbCompany;
int dbcompany = DbCompany;
}
访问变量如果您的财产“公共”,如果你想通过子类访问它,你甚至可以访问类之外的值,并“保护”。
我相信使用属性是一个更好的方式去。我希望这有帮助。
你不能,但如果你解释为什么你需要这个,我们可能能够找到解决方法 – Domysee
你不能像那样访问它们。你想要达到什么目的? – Shetty