c#基础学习(0806)之可变参数、ref和out关键字的简单使用

params可变参数:

1、无论方法有几个参数,可变参数必须出现再参数列表的最后,可以为可变参数直接传递一个对应类型的数组;

2、可变参数可以传递参数也可以不传递参数,如果不传递参数,则数组为一个长度为0的数组

3、可变参数可以直接传递一个数组进来

        static void Test(string msg,params int[] args)
        {
            //如果可变参数传值为null时,需要加上判断
            if (args != null)
            {

            }
        }

ref关键字:

1、参数再传递之前必须赋值,再方法钟可以不为ref参数赋值,可以直接使用

2、应用场景内部对外部的值直接改变

3、reg仅仅是一个地址,引用传递,可以把值传递强制改为引用传递

static void Main(string[] args)
{
  #region 交换两个变量
  int m=10,x=20;
  Swap(ref m, ref x);
  Console.WriteLine(m);
  Console.WriteLine(x);
  Console.ReadKey();
#endregion }
static void Swap(ref int n1, ref int n2) { int tmp=n1; n1=n2; n2=tmp; }

out关键字:

1、在方法中必须为out参数赋值

2、out参数的变量再传递之前不需要赋值,即使赋值了也不能在方法中使用,因为out参数无法获取传递进来的变量中的值,只能为传递进来的变量赋值,并且在方法执行完毕之前,必须赋值

static void Main(string[] args)
{
    #region 用户登录练习
    while (true)
    {
        Console.WriteLine("请输入用户名:");
        string uid = Console.ReadLine();
        Console.WriteLine("请输入密码:");
        string pwd = Console.ReadLine();
        string msg;
        bool isOk = ValidUserLogin(uid, pwd, out msg);
        if (isOk)
        {
            Console.WriteLine("登录成功====={0}",msg);
        }
        else
        {
            Console.WriteLine("登录失败===={0}",msg);
        }
    }
    #endregion
}

private static bool ValidUserLogin(string uid, string pwd, out string msg)
{
    bool isOk = false;
    if (uid != "admin")
    {
        msg = "用户名错误";
    }
    else if (pwd != "888888")
    {
        msg = "密码错误";
    }
    else
    {
        isOk = true;
        msg = "欢迎用户:" + uid;
    }
    return isOk;
}

 

posted @ 2018-08-06 14:56  超哥20  阅读(243)  评论(0编辑  收藏  举报