C#参量参数、输出参数、引用参数、值参数

参量参数:(params 关键字)

多个变量可以由一个参量参数来代表

代码:

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();
   }

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

      int[] myarray = new int[3] {10,11,12};
      UseParams(myarray);
   }
}输出
1
2
3

1
a
test

10
11
12

 

输出参数、引用参数:(out、ref关键字)

out调用者必须在调用方法之后初始化参数的值

ref调用者必须在调用方法之前首先初始化参数的值

代码:

 class Program
    {
        static void Main(string[] args)
        {
            //输出参数
            Point p = new Point(10, 12);
            int x, y;//输出参数不需要赋初值
            p.GetPoint(out x, out y);
            Console.WriteLine("p({0},{1})", x, y);
            //引用参数
            Point2 p1 = new Point2(12, 23);
            int x1 = 0, y1 = 0;//引用参数一定要赋初值
            p1.GetPoint(ref x1, ref y1);
            Console.WriteLine("p1({0},{1})", x1, y1);
            // 参数数组
            int[] a = { 1, 2, 3, 4, 5 };
            Array.F(a);
            Array.F(10, 20, 30, 60, 50);//F(new int[] {10, 20, 30, 60, 50})
            Array.F();
            Console.ReadLine();
        }
    }
    /// <summary>
    /// 输出参数可返回多个值
    /// </summary>
    class Point
    {
    
        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
        public void GetPoint(out int x, out int y)
        {
            y = this.Y;
            x = this.X;
        }
        private int X, Y;
    }
    /// <summary>
    /// 引用参数
    /// </summary>
    class Point2
    {
        int X, Y;
        public Point2(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
        public void GetPoint(ref int x, ref int y)
        {
            y = this.Y;
            x = this.X;
        }
    }
    /// <summary>
    /// 参数数组
    /// </summary>
    class Array
    {
        public static void F(params int[] args)
        {
            Console.WriteLine("数组长度为:{0}", args.Length);
            foreach (int i in args)
            {
                Console.WriteLine("{0}", i);
            }
            Console.WriteLine();
        }
    }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦里仙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值