c#ref和out的区别

Posted on 2018-07-08 11:37  肥猫097  阅读(172)  评论(0编辑  收藏  举报

ref:调用前需要赋值,用于传递参数的引用,而不是值.(有进有出)

out:方法内赋值,将值从方法内传到了方法外.(只出不进)

两者都属于引用传递;

 1         #region ref和out的区别
 2         /*
 3         ref:调用前需要赋值,用于传递参数的引用,而不是值.(有进有出)
 4 
 5         out:方法内赋值,将值从方法内传到了方法外.(只出不进)
 6 
 7         两者都属于引用传递;
 8         */
 9             string uid = "admin";
10             string pwd = "111111";  //正确登录密码为"666666",此处为错误密码
11             string msg = null;
12             if (CheckLogin(uid, pwd, out msg))
13             {
14                 Console.WriteLine("登录成功");
15             }
16             else
17             {
18                 Console.WriteLine("登录失败,错误原因是"+msg);
19             }
20             
21             #endregion
 1         public static bool CheckLogin(string uid , string pwd , out string msg )
 2         {
 3             if (uid == "admin" && pwd == "666666")  //账号密码正确,msg为空,登录成功
 4             {
 5                 msg = null;
 6                 return true;
 7             }
 8             else
 9             {
10                 msg = "用户名或密码错误";
11                 return false;
12             }
13         }

把out换成ref结果一样.

Copyright © 2024 肥猫097
Powered by .NET 9.0 on Kubernetes