核心规则
方法内部必须初始化:在方法体中,必须在方法返回前对
out
参数显式赋值(未赋值会导致编译错误)调用时无需初始化:调用方传递
out
参数前不需要初始化变量(可直接使用未赋值的局部变量)
下面是示例代码
static void Main(string[] args)
{Console.WriteLine("请输入用户名");string thisname = Console.ReadLine();Console.WriteLine("请输入密码");string thispwd=Console.ReadLine();string thismsg;bool thisresult= userpwd(thisname, thispwd, out thismsg);Console.WriteLine("{0}", thismsg);Console.WriteLine("登录状态为{0}", thisresult);Console.ReadKey();
}//out 参数需要在函数体内部初始化,然后引用的时候无需初始化
public static bool userpwd(string username,string pwd,out string msg)
{if (username=="admin" && pwd=="0000"){msg = "登录成功";return true;}else if (username == "admin"){msg = "登录失败";return false;}else if (pwd == "admin"){msg = "登录失败";return false;}else{msg = "未知错误";return false;}}
与ref的对比