C#函数的参数中返回结构数组
2024-07-21 02:19:21
供稿:网友
实例:
/// <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);
}
}
}