您当前的位置: 首页 >  ar

令狐掌门

暂无认证

  • 2浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#基础(三):函数(方法)的定义、out、ref、params

令狐掌门 发布时间:2020-05-01 16:16:42 ,浏览量:2

C#是纯面向对象的,和C++有点不同,比如C#的方法声明格式如下:

[public] static 返回值类型 方法名字(参数列表) {     方法体 }

public 访问修饰符,可以省略

比C++多了个修饰符,而且都得用static修饰, 静态函数只能访问静态成员 。其它的和C++基本一致。

C#有类似于C++的引用传值,用out和ref可以实现

(1)out修饰形参的用法
using System;

namespace out关键字
{
    class Program
    {
        //在函数形参前加out关键字表示该参数也会被返回,有点类似C++的引用传值,形参可以有多个out参数
        static int testOut(int num, out string str)
        {
            str = "success";
            return num;
        }

        static void Main(string[] args)
        {
            string str;

            //参数传到形参时也得加上out
            int ret = testOut(12, out str);

            Console.WriteLine("ret = {0}, str = {1}", ret, str);
            Console.ReadKey();
        }
    }
}
(2)ref修饰形参的用法
using System;

namespace ref关键字
{
    class Program
    {
        static void setMoney(ref int money)
        {
            money += 1000;
        }

        static void Main(string[] args)
        {
            int salary = 2000;

            //使用ref时,该参数必须在方法外赋值,实参前面也得用ref修饰
            setMoney(ref salary);
            Console.WriteLine("salary = " + salary);
            Console.ReadKey();
        }
    }
}
(3) params
using System;

namespace params关键字的使用
{
    class Program
    {
        static void Main(string[] args)
        {
            int max = getMax(12, 45, 11, 89, 6);

            Console.WriteLine("最大的数是: " + max);
            Console.ReadKey();
        }

        //params表示参数可以传入任意个int型的数,组成数组
        //params使用的时候,函数的参数列表只有一个参数,有多个参数时只能作为最后一个参数
        static int getMax(params int[] array)
        {
            int max = 0;
            foreach(var it in array)
            {
                if (max             
关注
打赏
1652240117
查看更多评论
0.0478s