zoukankan      html  css  js  c++  java
  • c#中参数关键字params、ref、out

    params:指定在参数数目可变处采用参数的方法参数;它后面不允许任何其它参数,并且只允许有一个params参数。

    params
    // cs_params.cs
    using System;
    public class MyClass
    {

    public static void UseParams(params int[] list)
    {
    for (int i = 0 ; i < list.Length; i++)
    {
    Console.WriteLine(list[i]);
    }
    Console.WriteLine();
    }

    public static void UseParams2(params object[] list)
    {
    for (int i = 0 ; i < list.Length; i++)
    {
    Console.WriteLine(list[i]);
    }
    Console.WriteLine();
    }

    static void Main()
    {
    UseParams(
    1, 2, 3);
    UseParams2(
    1, 'a', "test");

    // An array of objects can also be passed, as long as
    // the array type matches the method being called.
    int[] myarray = new int[3] {10,11,12};
    UseParams(myarray);
    }
    }

    ref使参数按引用传递;其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;传递到 ref 参数的参数必须最先初始化,这与 out 不同,out 的参数在传递之前不需要显式初始化。

    ref
    class RefExample
    {
    static void Method(ref int i)
    {
    i
    = 44;
    }
    static void Main()
    {
    int val = 0;
    Method(
    ref val);
    // val is now 44
    }
    }

    out使参数按引用传递;其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;传递到out参数的参数需要调用方法以便在方法返回之前赋值,这与ref不同,ref的参数在传递之前需要显式初始化。

    out
    class OutExample
    {
    static void Method(out int i)
    {
    i
    = 44;
    }
    static void Main()
    {
    int value;
    Method(
    out value);
    // value is now 44
    }
    }

  • 相关阅读:
    B树,B+树比较
    Kafka、RabbitMQ、RocketMQ 全方位对比
    ElasticSearch 笔记
    AtomicReference实现单例模式
    Netty 核心组件笔记
    Netty Reactor 线程模型笔记
    urldecode和urlencode相互转换
    python字符格式问题SyntaxError: Non-UTF-8 code starting with 'xe4'
    百度文字识别获取access token
    Python中MD5加密
  • 原文地址:https://www.cnblogs.com/zengen/p/1998457.html
Copyright © 2011-2022 走看看