如何将getter和setter参数传递给连接类
本文关键字:参数传递 连接 setter getter | 更新日期: 2023-09-27 18:29:53
我将文本框输入分配给getter,setter还创建了一个连接类。如何将getter和setter参数传递给连接类,以便在主窗体中使用它。
成员类别
private string srDatabase = "";
private string srID = "";
private string srPass = "";
public string SDB
{
get
{
return srDatabase;
}
set
{
srDatabase= value;
}
}
public string SID
{
get
{
return srID ;
}
set
{
srID = value;
}
}
public string SPassword
{
get
{
return srPass ;
}
set
{
srPass = value;
}
}
ConnectionClass
class Connection
{
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(dataSource) && !string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
con = new OracleConnection("Data Source=" + dataSource + ";User Id=" + userName.ToUpper() + ";Password=" + password + ";");
return con;
}
return con;
}
}
主窗体
UserMembers = new UserMembers();
txtSrcUserDatabase.Text = src.srDatabase ;
txtSrcUserID.Text=src.srID.ToUpper();
txtSrcUserPassword.Text = src.srPass;
OracleConnection conn1 = Connection.GetConnection() // **here error**
conn1.Open();
using (OracleCommand Names = new OracleCommand("SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME", conn1))
{
using (OracleDataReader reader = Names.ExecuteReader())
{
while (reader.Read())
{
//Do something
}
}
}
GetConnection方法需要三个参数。您需要将它们传递给方法。
UserMembers src = new UserMembers();
src.srDatabase =txtSrcUserDatabase.Text;
src.srID = txtSrcUserID.Text.ToUpper();
src.srPass = txtSrcUserPassword.Text;
OracleConnection conn1 = Connection.GetConnection(src.srDatabase, src.srID, src.srPass)
conn1.Open();
......
或者,您可以将UserMembers的实例传递给GetConnection方法,创建一个GetConnection的重载,如以下
class Connection
{
// the first overload that takes 3 string parameters
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
....
}
// The second overload that takes an instance of UserMembers
public static OracleConnection GetConnection(UserMembers src )
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(sr.srDatabase) && !string.IsNullOrWhiteSpace(sr.srID) && !string.IsNullOrWhiteSpace(sr.srPass))
{
con = new OracleConnection("Data Source=" + sr.srDatabase + ";User Id=" + sr.srID.ToUpper() + ";Password=" + sr.Pass + ";");
}
return con;
}
}
作为旁注。如果你需要srID成员总是大写,那么在setter属性中移动这个逻辑,当你试图读回时,你可能会停下来担心这个成员的正确格式
public string SID
{
get { return srID ; }
set { srID = value.ToUpper(); }
}