C#语法手册

方法声明示例


方法的参数,返回值,扩展方法,匿名方法的声明示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSGDemo.CSG019
{
    //https://docs.microsoft.com/zh-cn/dotnet/csharp/methods
    //https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-functions

    class DemoClass
    {

        //#csg019-01,实参与形参的说明
        //实参(实际参数)是在调用方法时传递的参数,形参(形式参数)是在方法中定义的参数。
        int AddMethod(int a, int b)
        {
            //a 和 b 为形参
            return a + b;
        }

        void DemoMethod()
        {
            //5 和 6 为实参
            AddMethod(5, 6);
        }


        //#csg019-02,普通参数
        void Method1(int intvalue, string str)
        {

        }

        //#csg019-03,可选参数,为参数设置默认值后,在调用时就可以选择是否传递该参数
        void Method2(string args = "default value")
        {

        }

        //#csg019-04,参数数组
        void Method3(params string[] strs)
        {

        }

        //#csg019-05,按引用传递参数 ref
        //使用 ref 关键字声明的参数为按引用传递,在方法调用传递该参数时也需要使用 ref 关键字。
        void Method4(ref int param1)
        {

        }

        //#csg019-06,参数传递关键字 out
        //out 关键字通过引用传递参数。 它让形参成为实参的别名,这必须是变量。
        //换而言之,对形参执行的任何操作都是对实参执行的。
        void Method5(out int param1)
        {
            param1 = 1;
        }

        //#csg019-07,参数传递关键字 in,in 关键字会导致按引用传递参数,但确保未修改参数。
        //使用 in 关键字声明的参数为按引用传递,
        //
        public void Method6(in int param1)
        {

        }

        //#csg019-08,单个返回值
        string Method7()
        {
            return "string value";
        }


        //#csg019-09,可以使用元组来实现多个值的返回
        public (int, string) Method8()
        {
            return (1, "str");
        }



        public void DemoMethod9()
        {
            //匿名函数是一个“内联”语句或表达式,可在需要委托类型的任何地方使用。
            //#csg019-10,使用匿名函数声明创建委托实例
            Func<string,int> act1 = delegate (string s) { return 1; };

            //使用lambada表达式创建委托实例
            Func<string, int> act = new Func<string, int>((str) => 1);
        }

    }


    //#csg019-11,扩展方法声明
    public static class Extensions
    {
        //为string类扩展方法
        public static int ExMethod(this string str)
        {
            return Convert.ToInt32(str);
        }

    }

}