Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Gọi phương thức tùy chỉnh (Custom Methods) trong C#

Custom Method (Phương thức tùy chỉnh) là phương thức do lập trình viên định nghĩa để đóng gói logic tái sử dụng. Cú pháp:

access static? ReturnType MethodName(ParamType paramName, ...)
{
    // Method body
    return value; // Nếu non-void
}

Ví dụ: Kiểm tra Palindrome nhị phân

using System;

public class Demo
{
    // Custom method: Đảo ngược bit của long
    public static long ReverseBits(long num)
    {
        long rev = 0;
        while (num > 0)
        {
            rev <<= 1;           // Dịch trái 1 bit
            if ((num & 1) == 1)  // Kiểm tra bit thấp nhất
                rev ^= 1;        // Set bit thấp nhất của rev
            num >>= 1;           // Dịch phải num
        }
        return rev;
    }
    
    // Custom method: Kiểm tra palindrome
    public static bool IsBinaryPalindrome(long num)
    {
        long reversed = ReverseBits(num);
        return num == reversed;
    }
    
    public static void Main()
    {
        long num = 5; // Binary: 101
        
        Console.WriteLine($"Số: {num} (Binary: {Convert.ToString(num, 2)})");
        
        if (IsBinaryPalindrome(num))
            Console.WriteLine("Palindrome Number");
        else
            Console.WriteLine("Not a Palindrome Number");
        
        // Test thêm
        Console.WriteLine($"\n9 (1001): {IsBinaryPalindrome(9)}");  // True
        Console.WriteLine($"10 (1010): {IsBinaryPalindrome(10)}"); // False
    }
}

Kết quả

Số: 5 (Binary: 101)
Palindrome Number

9 (1001): True
10 (1010): False

Các loại phương thức

LoạiCú phápĐặc điểm
Instance methodvoid Foo()Truy cập this, gọi qua instance
Static methodstatic void Foo()Không có this, gọi qua ClassName.Foo()
Extension methodstatic void Foo(this T t)Mở rộng type có sẵn, gọi như instance method
Local functionvoid Foo() { } trong methodChỉ dùng trong method chứa, capture variables
Anonymous/DelegateFunc<int,int> f = x => x*2;Delegate, lambda
Expression-bodiedint Square(int x) => x*x;Rút gọn cho 1 expression

Best Practices

  • Single Responsibility: Một method làm một việc.
  • Naming: PascalCase, động từ: CalculateTotal, GetUserById.
  • Parameters: Ít tham số (≤ 4), dùng object/record cho nhiều param.
  • Return: Tránh out/ref nếu có thể, dùng Tuple/Record trả về nhiều giá trị.
  • Pure functions: Không side effect, dễ test, dễ parallel.
  • XML Docs: /// cho public API.

Gọi method

// Static method
Demo.IsBinaryPalindrome(5);

// Instance method
var demo = new Demo();
demo.InstanceMethod();

// Extension method
"hello".CustomExtension();

// Delegate/Func
Func square = x => x * x;
square(5);