我们都知道,ref是传递参数的地址,out是返回值,两者有相同之处,不过也有不同的地方。

使用ref前必须对变量赋值,而out则不用。

out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。

以下摘自互联网------------------------------

using System;
class TestApp
{
 static void outTest(out int x, out int y)
 {//离开这个函数前,必须对x和y赋值,否则会报错。
  //y = x;
  //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
  x = 1;
  y = 2;
 }
 static void refTest(ref int x, ref int y)
 {
  x = 1;
  y = x;
 }
 public static void Main()
 {
  //out test
  int a,b;
  //out使用前,变量可以不赋值
  outTest(out a, out b);
  Console.WriteLine("a={0};b={1}",a,b);
  int c=11,d=22;
  outTest(out c, out d);
  Console.WriteLine("c={0};d={1}",c,d);

  //ref test
  int m,n;
  //refTest(ref m, ref n);
  //上面这行会出错,ref使用前,变量必须赋值

  int o=11,p=22;
  refTest(ref o, ref p);
  Console.WriteLine("o={0};p={1}",o,p);
 }
}

之前在用函数取返回值(要取两个以上字段)时总是用拼接再拆分的方法,经常使用这种方法,拼完折觉得挺麻烦的,今天看了以上例子,觉得使用这种方式就不用再拼/折了,

 

public void CheckStatNow(out string pnr,out int stat_now,string orderhao)
    {
        try
        {
            SqlConnection conn = bd.SqlConn();
            string sql = "select pnr_code,order_stat from orderlist where order_hao=" + orderhao;
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                pnr = reader["pnr_code"].ToString().Trim();
                stat_now = Convert.ToInt32(reader["order_stat"].ToString());
            }
            else//这里一定要写不能偷懒哦,因为我们使用Out函数,这两个参数都要进行赋值的,就像使用Return的函数一样
            {
                pnr = "00000";
                stat_now = 0;
            }
            cmd.Dispose();
            conn.Close();
        }
        catch
        {
            pnr = "00000";
            stat_now = 0;
        }
    }

 

以下是如何使用:

               //取当前订单状态及当前pnr
                string pnr_this;//看看这里不用先赋值
                int orderstat_this;//看看这里不用先赋值
                CheckStatNow(out pnr_this, out orderstat_this, orderhao.ToString());

经过以上方法的调用 我们就可以直接Response.Write(orderstat_this.ToString())了,怎么样?是比拼接方法好用了吧?

 posted on 2009-01-19 17:36  dongpo  阅读(577)  评论(0编辑  收藏  举报