Home > Backend Development > C#.Net Tutorial > [c# tutorial] C# method

[c# tutorial] C# method

黄舟
Release: 2016-12-26 14:22:25
Original
1298 people have browsed it

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
}
Copy after login

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;
   }
   ...
}
Copy after login

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();
      }
   }
}
Copy after login

When the above code is compiled and executed, it produces the following results:

最大值是: 200
Copy after login
Copy after login

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();

        }
    }
}
Copy after login

When the above code is compiled and executed, it produces the following results:

最大值是: 200
Copy after login
Copy after login

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();

        }
    }
}
Copy after login

When the above code is compiled and executed, it produces the following results:

6 的阶乘是: 720
7 的阶乘是: 5040
8 的阶乘是: 40320
Copy after login

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();
        }
    }
}
Copy after login

When the above code is compiled and executed, it produces the following results:

在交换之前,a 的值:100
在交换之前,b 的值:200
在交换之后,a 的值:100
在交换之后,b 的值:200
Copy after login

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();

      }
   }
}
Copy after login

当上面的代码被编译和执行时,它会产生下列结果:

在交换之前,a 的值:100
在交换之前,b 的值:200
在交换之后,a 的值:200
在交换之后,b 的值:100
Copy after login

结果表明,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();

      }
   }
}
Copy after login

当上面的代码被编译和执行时,它会产生下列结果:

在方法调用之前,a 的值: 100
在方法调用之后,a 的值: 5
Copy after login

提供给输出参数的变量不需要赋值。当需要从一个参数没有指定初始值的方法中返回值时,输出参数特别有用。请看下面的实例,来理解这一点:

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();
      }
   }
}
Copy after login

当上面的代码被编译和执行时,它会产生下列结果(取决于用户输入):

请输入第一个值:
7
请输入第二个值:
8
在方法调用之后,a 的值: 7
在方法调用之后,b 的值: 8
Copy after login

 以上就是【c#教程】C# 方法的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template