C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# 函数

C# 函数

函数是具有签名的代码块。函数用于执行代码块中指定的语句。一个函数由以下部分组成:
函数名: 它是用于进行函数调用的唯一名称。
返回类型: 用于指定函数返回值的数据类型。
主体: 是一个包含可执行语句的块。
访问说明符: 用于指定应用程序中的函数可访问性。
参数: 参数列表

C# 函数语法

<access-specifier><return-type>FunctionName(<parameters>)
{
// function body
// return statement
}
访问说明符、参数和返回语句是可选的。
让我们看一个示例,其中我们创建了一个返回字符串值并接受字符串参数的函数。

C# 函数: 不使用参数和返回类型

不返回任何值的函数指定 void 类型作为返回类型。在以下示例中,创建了一个没有返回类型的函数。
using System;
namespace FunctionExample
{
    class Program
    {
        // User defined function without return type
        public void Show() // No Parameter
        {
            Console.WriteLine("this is non parameterized function");
            // No return statement
        }
        // Main function, execution entry point of the program
        static void Main(string[] args)
        {
            Program program = new Program(); // Creating Object
            program.Show(); // Calling Function           
        }
    }
}
输出:
this is non parameterized function

C# 函数: 使用参数但没有返回类型

using System;
namespace FunctionExample
{
    class Program
    {
        // User defined function without return type
        public void Show(string message)
        {
            Console.WriteLine("Hello " + message);
            // No return statement
        }
       // Main function, execution entry point of the program
        static void Main(string[] args)
        {
            Program program = new Program(); // Creating Object
            program.Show("Rahul Kumar"); // Calling Function           
        }
    }
}
输出:
Hello Rahul Kumar
一个函数可以有零个或任意数量的参数来获取数据。在以下示例中,创建了一个不带参数的函数。没有参数的函数也称为非参数化函数。

C#函数: 使用参数和返回类型

using System;
namespace FunctionExample
{
    class Program
    {
        // User defined function
        public string Show(string message)
        {
         Console.WriteLine("Inside Show Function");
         return message;
        }
        // Main function, execution entry point of the program
        static void Main(string[] args)
        {
            Program program = new Program();
            string message = program.Show("Rahul Kumar");
            Console.WriteLine("Hello "+message);
        }
    }
}
输出:
Inside Show Function
Hello Rahul Kumar
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4