C# method
A method is to organize some related statements together to form a block of statements used to perform a task. Every C# program has at least one class with a Main method.
To use a method, you need to:
Define the method
Call the method
Define the method in C#
When defining a method , you are essentially declaring an element of its structure. In C#, the syntax for defining a method is as follows:
<Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body }
The following are the various elements of the method:
Access Specifier: Access modifier, which determines the visibility of a variable or method to another class .
Return type: Return type, a method can return a value. The return type is the data type of the value returned by the method. If the method does not return any value, the return type is void.
Method name: The method name is a unique identifier and is case-sensitive. It cannot be the same as other identifiers declared in the class.
Parameter list: Parameter list, enclosed in parentheses, is used to pass and receive method data. The parameter list refers to the method's parameter types, order, and number. Parameters are optional, that is, a method may contain no parameters.
Method body: Method body, which contains the set of instructions required to complete the task.
Example
The code snippet below shows a function FindMax that accepts two integer values and returns the larger of the two. It has public access modifier, so it can be accessed from outside the class using an instance of the class.
class NumberManipulator { public int FindMax(int num1, int num2) { /* 局部变量声明 */ int result; if (num1 > num2) result = num1; else result = num2; return result; } ... }
Calling methods in C#
You can call a method using its name. The following example demonstrates this:
using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* 局部变量声明 */ int result; if (num1 > num2) result = num1; else result = num2; return result; } static void Main(string[] args) { /* 局部变量定义 */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //调用 FindMax 方法 ret = n.FindMax(a, b); Console.WriteLine("最大值是: {0}", ret ); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following results:
最大值是: 200
You can also use an instance of a class from another class Call public methods of other classes. For example, the method FindMax belongs to the NumberManipulator class and you can call it from another class Test .
using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* 局部变量声明 */ int result; if (num1 > num2) result = num1; else result = num2; return result; } } class Test { static void Main(string[] args) { /* 局部变量定义 */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //调用 FindMax 方法 ret = n.FindMax(a, b); Console.WriteLine("最大值是: {0}", ret ); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following results:
最大值是: 200
Recursive method call
A method can call itself. This is called recursion. The following example uses a recursive function to calculate the factorial of a number:
using System; namespace CalculatorApplication { class NumberManipulator { public int factorial(int num) { /* 局部变量定义 */ int result; if (num == 1) { return 1; } else { result = factorial(num - 1) * num; return result; } } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); //调用 factorial 方法 Console.WriteLine("6 的阶乘是: {0}", n.factorial(6)); Console.WriteLine("7 的阶乘是: {0}", n.factorial(7)); Console.WriteLine("8 的阶乘是: {0}", n.factorial(8)); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following results:
6 的阶乘是: 720 7 的阶乘是: 5040 8 的阶乘是: 40320
Parameter passing
When calling a method with parameters, you need to pass the parameters to the method. In C#, there are three ways to pass parameters to methods:
Method
Description
Value parameter This method copies the actual value of the parameter to the formal parameter of the function. The actual parameter and the formal parameter use two different values in memory. In this case, when the value of the formal parameter changes, the value of the actual parameter will not be affected, thus ensuring the security of the actual parameter data.
Reference parameters This method copies the reference to the memory location of the parameter to the formal parameter. This means that when the value of the formal parameter changes, the value of the actual parameter also changes.
Output parameters This method can return multiple values.
Pass parameters by value
This is the default way of parameter passing. In this manner, when a method is called, a new storage location is created for each value parameter.
The value of the actual parameter will be copied to the formal parameter. The actual parameter and the formal parameter use two different values in memory. Therefore, when the value of the formal parameter changes, the value of the actual parameter will not be affected, thus ensuring the security of the actual parameter data. The following example demonstrates this concept:
using System; namespace CalculatorApplication { class NumberManipulator { public void swap(int x, int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 temp 赋值给 y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int b = 200; Console.WriteLine("在交换之前,a 的值: {0}", a); Console.WriteLine("在交换之前,b 的值: {0}", b); /* 调用函数来交换值 */ n.swap(a, b); Console.WriteLine("在交换之后,a 的值: {0}", a); Console.WriteLine("在交换之后,b 的值: {0}", b); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following results:
在交换之前,a 的值:100 在交换之前,b 的值:200 在交换之后,a 的值:100 在交换之后,b 的值:200
The result shows that even if the value is changed within the function, the value Nothing has changed.
按引用传递参数
引用参数是一个对变量的内存位置的引用。当按引用传递参数时,与值参数不同的是,它不会为这些参数创建一个新的存储位置。引用参数表示与提供给方法的实际参数具有相同的内存位置。
在 C# 中,使用 ref 关键字声明引用参数。下面的实例演示了这点:
using System; namespace CalculatorApplication { class NumberManipulator { public void swap(ref int x, ref int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 temp 赋值给 y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int b = 200; Console.WriteLine("在交换之前,a 的值: {0}", a); Console.WriteLine("在交换之前,b 的值: {0}", b); /* 调用函数来交换值 */ n.swap(ref a, ref b); Console.WriteLine("在交换之后,a 的值: {0}", a); Console.WriteLine("在交换之后,b 的值: {0}", b); Console.ReadLine(); } } }
当上面的代码被编译和执行时,它会产生下列结果:
在交换之前,a 的值:100 在交换之前,b 的值:200 在交换之后,a 的值:200 在交换之后,b 的值:100
结果表明,swap 函数内的值改变了,且这个改变可以在 Main 函数中反映出来。
按输出传递参数
return 语句可用于只从函数中返回一个值。但是,可以使用 输出参数 来从函数中返回两个值。输出参数会把方法输出的数据赋给自己,其他方面与引用参数相似。
下面的实例演示了这点:
using System; namespace CalculatorApplication { class NumberManipulator { public void getValue(out int x ) { int temp = 5; x = temp; } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; Console.WriteLine("在方法调用之前,a 的值: {0}", a); /* 调用函数来获取值 */ n.getValue(out a); Console.WriteLine("在方法调用之后,a 的值: {0}", a); Console.ReadLine(); } } }
当上面的代码被编译和执行时,它会产生下列结果:
在方法调用之前,a 的值: 100 在方法调用之后,a 的值: 5
提供给输出参数的变量不需要赋值。当需要从一个参数没有指定初始值的方法中返回值时,输出参数特别有用。请看下面的实例,来理解这一点:
using System; namespace CalculatorApplication { class NumberManipulator { public void getValues(out int x, out int y ) { Console.WriteLine("请输入第一个值: "); x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("请输入第二个值: "); y = Convert.ToInt32(Console.ReadLine()); } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a , b; /* 调用函数来获取值 */ n.getValues(out a, out b); Console.WriteLine("在方法调用之后,a 的值: {0}", a); Console.WriteLine("在方法调用之后,b 的值: {0}", b); Console.ReadLine(); } } }
当上面的代码被编译和执行时,它会产生下列结果(取决于用户输入):
请输入第一个值: 7 请输入第二个值: 8 在方法调用之后,a 的值: 7 在方法调用之后,b 的值: 8
以上就是【c#教程】C# 方法的内容,更多相关内容请关注PHP中文网(www.php.cn)!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
