在C#中如何在函數參數中返回結構數組?
最後更新:2017-02-28
來源:互聯網
上載者:User
函數|數組 頭暈腦漲地研究了一天,就為了實現在函數的參數中返回結構數組。
現供大家分享,節省學習時間。
執行個體:
/// <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);
}
}
}