asp.net开发中什么时候用到out或者ref 看到有些项目中别人会用到这些 但是我不明白为什么要用

解决方案 »

  1.   

    ref引用传递,被传递的对象需要被实例化后再传参,而out不需要事先实例化。
    在函数需要多个返回值的时候或需要函数修改对应参数的时候使用
      

  2.   

    如:做个登陆的界面,判断用户密码是否正确(bool),如果不正确则返回原因.  public bool UserLogin(string UserName,string Pwd,out string Info)
      { 
           if(UserName==null || UserName.Trim()=="")
           {
             Info="用户名不能为空.";
             return false;
           }
          if(UserName=="a" && Pwd=="b")
           {
              Info="成功验证.";
              return true;
           }
          else
           {
              Info="用户名或密码出错.";
              return false;
           }
      }
       调用:
         string msg;
         bool login=UserLogin("a","b",out msg);
         if(login)
          {
             //登陆代码
          }
         else
          {
             //弹出错误: msg
             Message.Show(msg) //Winfrom
          }
      

  3.   

    MessageBox.Show(msg) //Winfrom
      

  4.   

    ref:如:计算一个面积,但只有高度>100 宽度>100时才变更原来的面积大小,否则按原来的面积.  static void Main(string[] args)
            {
                int a = 100; //原来的值,或者是由某种条件下计算出来的值.
                Account(50, 50, ref a); //执行变更
                // a=100  条件达不到,所有不变会
                Account(200, 200, ref a);  //执行变更
                // a=200  达到条件,变更面积
            }        public static void Account(int w, int h, ref int a)
            {
                if (w > 100 && h > 100)
                {
                    a = w * h;
                }
            }
      

  5.   

    你的方法如果需要传回多个值就用OUT或者REF