C# Param parameters types

本文展示C#中使用params关键字处理可变参数的方法及内部实现细节,包括处理空参数、空参数列表、参数初始化和参数传递等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You can define a method to have 'params' type of argument, with the 'params', you can pass argument as you can do in variable arguments as in C++/C.

 

 

Here is one example that shows you some tricks and internals with the params in C#.

 

 

class Program
  {
    static void Main(string[] args)
    {
      // you can pass an null, the param parameter is null
      ParamMethods(null);
      // you can pass an empty parameter list, which is like pass a 0-length list
      ParamMethods();
      // or you can enumerate the list and pass any number of parameters, the compiler
      // will generate a list, initialize the param array with the list values.
      ParamMethods("Hello3", "world3");
      // or you can explicitly pass in an array, and you can do the initialization yourself.
      ParamMethods(new [] { "Hello4", "World4"});
    }


    internal static void ParamMethods(params string[] param)
    {
      if (param == null)
      {
        param = new[] { "hello", "world" };
        Console.WriteLine("param is null");
        return;
      }

      if (param.Length == 0)
      {
        param = new[] { "hello2", "world2" };
        Console.WriteLine("param.Length == 0");
        return;
      }


      int i = 0;
      foreach (var item in param)
      {
        ++i;
        Console.WriteLine(i.ToString() + ": " + item);

      }
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值