如何在 C# 中定義自定義方法?


要在 C# 中定義自定義方法,請使用以下語法 -

<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}

以下是方法的各個組成部分 -

  • 訪問說明符 - 這決定了從另一個類中訪問變數或方法的可見性。

  • 返回型別 - 方法可以返回一個值。返回型別是方法返回的值的資料型別。如果該方法不返回任何值,則返回型別為 void

  • 方法名稱 - 方法名稱是唯一識別符號,並區分大小寫。它不能與類中宣告的任何其他識別符號相同。

  • 引數列表 - 括在圓括號中,引數用於從方法傳遞和接收資料。引數列表是指型別、順序和方法引數的數量。引數是可選的;也就是說,方法可以不包含任何引數。

  • 方法正文 - 包含完成所需活動所需的一組指令。

讓我們看一個示例 -

示例

 動態演示

using System;

namespace Demo {
   class NumberManipulator {
      public int FindMax(int num1, int num2) {
         /* local variable declaration */
         int result;

         if (num1 > num2)
         result = num1;
         else
         result = num2;
         return result;
      }

      static void Main(string[] args) {
         /* local variable definition */
         int a = 90;
         int b = 15;
         int ret;
         NumberManipulator n = new NumberManipulator();

         //calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is : {0}", ret );
         Console.ReadLine();
      }
   }
}

輸出

Max value is : 90

更新時間:2020 年 6 月 20 日

943 次瀏覽

開啟你的事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.