C# 函数

out

当一个函数(方法)有不同类型的返回值时,可以使用out参数。

class Program
{
    static void Main(string[] args)
    {
        int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int max = 0, min = 0, sum = 0, avg = 0;
        string a;
        bool b;
        double c;
        Test(nums, out max, out min, out sum, out avg, out a, out b, out c);
        Console.WriteLine(max);
        Console.WriteLine(min);
        Console.WriteLine(sum);
        Console.WriteLine(avg);
        Console.WriteLine(a); 
        Console.WriteLine(b);
        Console.WriteLine(c);

    }
    public static void Test(int[] nums, out int max, out int min, out int sum, out int avg, out string a, out bool b, out double c)
    {
        max = nums[0];
        min = nums[1];
        sum = nums[2];
        avg = nums[3];
        a = "hello world";
        b = true;
        c = 1.23123;
    }
}

Ref

使用ref后可以将变量带入方法改变,并带出。
使用ref的参数外必须赋值,而在方法内可以不赋值。

static void Main()
    {
        int a = 5000;
        Test(ref a);
        Console.WriteLine(a);
    }

    public static void Test(ref int a)
    {
        a += 500;
    }

Params

当不想定义变量传参数到函数中时, 可以使用params 关键字
Params 关键字必须是形参最后一个元素, 且一个函数只能有一个params。

static void Main()
    {
        Test("Hello",17,13,14);
    }
public static void Test(string name, params int[] nums)
    {
        int size = nums.Length;
        Console.WriteLine(size);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Anunnaki_IO

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

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

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

打赏作者

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

抵扣说明:

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

余额充值