我有一个包含类的类库。该类负责在程序和数据库之间建立连接,并为我提供连接字符串:
public class DBcon
{
private string pass = "";
private string dbName = "";
OleDbConnection con = new OleDbConnection();
public string setdbName
{
set { dbName = value; }
}
public string setpass
{
set { pass = value; }
}
public OleDbConnection getsetcon
{
set { createcon(); }
get { return con; }
}
private void createcon()
{
PathFinder dbPath = new PathFinder(); // just another class
string DBPath = "";
dbPath.dbFilesPath = "db";
dbPath.setDBName = dbName;
DBPath = dbPath.dbFilesPath;
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
"Persist Security Info = False;Jet OLEDB:Database Password=" + pass + "";
}
}
首先,我想使用公共方法,即。 createcon,以避免所有属性,但后来我读到这是一个不好的做法。 然后我决定使用只写属性,但它们也被认为是不好的做法。
任何人都可以告诉我该怎么做才能使我的班级成为一个结构合理的班级。我正在使用只写属性,因为我不想返回字符串。我只想要OledbConnection。
即使改变了班级的结构,任何帮助都会受到赞赏。
答案 0 :(得分:2)
public class DBConnection
{
private string pass = string.Empty;
private string dbName = string.Empty;
private OleDbConnection connection;
public void DBConnection(string dbName, string pass)
{
this.dbName = dbName;
this.pass = pass;
this.Initialize();
}
public OleDbConnection Connection
{
get {return this.connection;}
}
private void Initialize()
{
//all the initialization
var connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
"Persist Security Info = False;Jet OLEDB:Database Password=" + pass + "";
this.connection = new OleDbConnection(connString);
}
}
P.S。而不是使用字符串连接,使用appropriate string builder作为连接路径。