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


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

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

要呼叫自定義方法,請嘗試執行以下程式碼。其中包括一個用於檢查二進位制表示是否是迴文的 checkPalindrome() 方法 -

示例

 即時演示

using System;

public class Demo {
   public static long funcReverse(long num) {
      long myRev = 0;

      while (num > 0) {
         myRev <<= 1;

         if ((num & 1) == 1)
         myRev ^= 1;
         num >>= 1;
      }
      return myRev;
   }
   public static bool checkPalindrome(long num) {
      long myRev = funcReverse(num);
      return (num == myRev);
   }
   public static void Main() {
      // Binary value of 5 us 101
      long num = 5;

      if (checkPalindrome(num))
      Console.WriteLine("Palindrome Number");
      else
      Console.WriteLine("Not a Palindrome Number");
   }
}

輸出

Palindrome Number

更新於: 20-Jun-2020

295 瀏覽

啟動您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.