【发布时间】:2016-03-31 08:51:59
【问题描述】:
我有一个需要在整个程序中使用的公共字符串。
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静态可能会起作用,但可能会导致其他问题,具体取决于您的应用)
标签: c# string methods properties