我正在慢慢学习 C#,对代码有点困惑。我在这里有一个简化版本的数据库连接设置类
public class DatabaseSettings
{
private static string connectionString = string.Empty;
public static string ConnectionString
{
get
{
return connectionString;
}
private set
{
connectionString = value;
}
}
public bool TestConnection()
{
bool _returnVal = false;
string _connectionString = String.Format("Data Source={0};Persist Security Info=False", databaseLocation);
using (SqlCeConnection connection = new SqlCeConnection(_connectionString))
{
try
{
connection.Open();
connectionString = _connectionString; // sets the value of the connection string here
_returnVal = true;
}
catch (SqlCeException e)
{
// other codes here
_returnVal = false;
}
finally
{
connection.Close();
}
}
return _returnVal;
}
// other methods here
}
现在在我的Main Class
,我很困惑这里发生了什么。当我尝试这段代码时:
string _databaseLocation = "database path";
DatabaseSettings _dbaseSetting = new DatabaseSettings(_databaseLocation, true);
_dbaseSetting.TestConnection();
string newConnectionString = _dbaseSetting.ConnectionString;
// ^ i got an error here
// Member 'SQLCE_Sample.ClassList.DatabaseSettings.ConnectionString.get'
// cannot be accessed with an instance reference;
// qualify it with a type name instead
下面这个可以正常工作,但问题是我得到了一个空字符串:
string _databaseLocation = "database path";
DatabaseSettings _dbaseSetting = new DatabaseSettings(_databaseLocation, true);
string newConnectionString = DatabaseSettings.ConnectionString;
我真正想要的是我需要创建一个类来public method
测试从应用程序到数据库的连接。该方法内部包含设置连接字符串值的语法。然后我还需要一个在不实例化类的情况下检索连接字符串的值(property
这就是我添加static
关键字的原因)。我怎么可能做到这一点?