asp.net中关于out的好处

我们都知道,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())了,怎么样?是比拼接方法好用了吧?

转载于:https://www.cnblogs.com/dongpo888/archive/2009/01/19/1378453.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值