黑马程序员技术交流社区
标题:
C#中ref和out的使用
[打印本页]
作者:
迷你卡卡
时间:
2013-10-22 19:40
标题:
C#中ref和out的使用
本帖最后由 迷你卡卡 于 2013-10-22 20:36 编辑
求教C#中ref和out这两个关键字一般在什么时候使用?是不是这两个关键字有时可以通用啊,ref引用传递,但是到底是怎么传递的啊,传递的是什么
作者:
Liu阳
时间:
2013-10-22 19:58
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test12
{
class Program
{
static void Main(string[] args)
{
//值传递变引用传递
int x = 20, y = 30;
swap(x, y);
Console.WriteLine("x={0},y={1}",x,y);
swap(ref x, ref y);
Console.WriteLine("x={0},y={1}", x, y);
Console.ReadKey();
}
static void swap(ref int x,ref int y)
{
int temp = x;
x = y;
y = temp;
}
static void swap(int x,int y)
{
int temp = x;
x = y;
y = temp;
}
}
}
复制代码
out 需要从方法中获取多个返回值用,调用函数的时候它不需要赋初值哦,函数退出前一定要给out参赋值哦
作者:
孙健
时间:
2013-10-22 20:14
static void Main(string[] args)
{
//登陆 除了返回true或者false之外,还要返回一条登陆信息。
Console.WriteLine("请输入一个用户名");
string name = Console.ReadLine();
Console.WriteLine("请输入一个密码");
string pwd = Console.ReadLine();
string str ;
bool b = IsLogin(name, pwd, out str);
Console.WriteLine("登陆结果:{0}",b);
Console.WriteLine("登陆信息:{0}",str);
Console.ReadKey();
}
public static bool IsLogin(string name, string pwd, out string msg)
{
bool isLogin = false;
if (name == "admin" && pwd == "888888")
{
isLogin = true;
msg = "登陆成功";
}
else if (name == "admin")
{
msg = "密码错误";
}
else if (pwd == "888888")
{
msg = "用户名错误";
}
else
{
msg = "未知错误";
}
return isLogin;
}
ref上层代码已经说明,out参数是多个返回值,IsLogin()方法主返回值是bool类型值;使用out传参还可以多返回一个传入的类型,注意:在方法体内部必须每个分支都要给out参数的赋值,如果不赋值或有分支程序赋不到值,程序会报错
作者:
迷你卡卡
时间:
2013-10-22 20:36
孙健 发表于 2013-10-22 20:14
static void Main(string[] args)
{
//登陆 除了返回true或者false之外,还 ...
呵呵,代码说的很清楚呢,多写了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2