头晕脑涨地研究了一天,就为了实现在函数的参数中返回结构数组。
现供大家分享,节省学习时间。
实例:
/// <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;