頭暈腦漲地研究了一天,就為了實現在函數的參數中返回結構數組。
現供大家分享,節省學習時間。
實例:
/// <summary>
/// 用戶信息結構
/// </summary>
public struct TUSER
{
public string LoginName;
public string LoginPass;
public string TrueName;
public string EMail;
public int Level;
}
/// <summary>
/// 獲得所有注冊用戶
/// </summary>
/// <param name="USERINFO">返回用戶信息結構</param>
public bool GetUsers(out TUSER[] G_USERINFO)
{
USEROP.TUSER[] f_TUSER;
int CurRec = 0; //初始化記錄計數器
int rec_count =0; //計算總記錄數
SqlConnection myConn = new SqlConnection(connectionString);
string cmd="select * from " +m_Table; //SQL查詢語句
SqlCommand mycmd=new SqlCommand(cmd,myConn);
mycmd.Connection.Open(); //打開連接
SqlDataReader adr = null; //創建數據讀取器
try
{
adr = mycmd.ExecuteReader();
while(adr.Read ())
{
rec_count += 1;
}
myConn.Close(); //關閉數據庫連接
mycmd.Connection.Open (); //打開數據庫連接
try
{
adr = mycmd.ExecuteReader ();
f_TUSER = new USEROP.TUSER[rec_count];
while(adr.Read())
{
f_TUSER[CurRec].LoginName = adr["US_LOGINNAME"].ToString();
f_TUSER[CurRec].LoginPass = adr["US_LOGINPASS"].ToString ();
f_TUSER[CurRec].TrueName = adr["US_TrueName"].ToString ();
f_TUSER[CurRec].EMail = adr["US_EMail"].ToString ();
f_TUSER[CurRec].Level = Int32.Parse (adr["US_Level"].ToString ());
CurRec += 1;
}
G_USERINFO = f_TUSER;
myConn.Close (); ///關閉連接
return true;
}
catch
{
myConn.Close();
f_TUSER = new USEROP.TUSER[1];
f_TUSER[0].LoginName = "";
f_TUSER[0].LoginPass = "";
f_TUSER[0].TrueName = "";
f_TUSER[0].EMail = "";
f_TUSER[0].Level = 0;
G_USERINFO = f_TUSER;
return false;
}
}
catch
{
myConn.Close ();
f_TUSER = new USEROP.TUSER[1];
f_TUSER[0].LoginName = "";
f_TUSER[0].LoginPass = "";
f_TUSER[0].TrueName = "";
f_TUSER[0].EMail = "";
f_TUSER[0].Level = 0;
G_USERINFO = f_TUSER;
return false;
}
///////////////// 在WEB FORM中調用如下:
private void Button3_Click(object sender, System.EventArgs e)
{
KSBM.USEROP.TUSER[] f_TUSER; // = new KSBM.USEROP.TUSER(); ///為什麼不"new" 一個結構數組呢?因為傳進來的已是我們要的數據了,所以只要開辟一個存儲空間就行了.
KSBM.USEROP f_USOP = new KSBM.USEROP();
bool ret=f_USOP.GetUsers (out f_TUSER); ///調用函數,取得結構數組及信息
if(f_TUSER.Length !=0) //數據長度為0時,表明無返回數據.
{
for(int iloop=0;iloop<f_TUSER.Length;iloop++) ///遍歷數組並輸出到客戶端的浏覽器
{
Response.Write (f_TUSER[iloop].LoginName);
Response.Write (f_TUSER[iloop].LoginPass);
Response.Write (f_TUSER[iloop].TrueName);
Response.Write (f_TUSER[iloop].EMail);
Response.Write (f_TUSER[iloop].Level);
}
}
}