我有一個公共字符串,我需要在整個程序中使用。傳遞方法之間的字符串值c#
public string connectionString = null;
我指定值,如下:
internal string accessString()
{
return connectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=" + DBFileName + ";" +
@"Persist Security Info=False";
}
當我運行的方法在第一時間值是正確的,但一旦方法執行完畢的值返回空值。
internal void selectDB()
{
try
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
DBFileName = choofdlog.FileName;
connectionString = accessString();
Saveproducts();
}
MessageBox.Show(connectionString);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}//select db ends
上述方法可以很好地得到值。
internal void writeContents()// read all the text files to the Data base
{
try
{
MessageBox.Show(connectionString);
}
}
上面的這個方法返回null,即使它在第二個方法之後運行已經成功地爲connectionString賦值了。
我怎樣才能解決這個問題,我不想使用靜態
請問您可以展示更多類的代碼嗎?你什麼時候調用'accessString()',什麼時候訪問'connectionString()'? –
很難確切知道你做錯了什麼,但可能是由於對象超出範圍的某個實例 - 需要更多的代碼來確認,所有當前的答案都是推測性的(儘管使'connectionString'靜態可以工作,但可能會導致其他問題根據你的應用程序) – Charleh