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ại | Cú pháp | Đặc điểm |
|---|---|---|
| Instance method | void Foo() | Truy cập this, gọi qua instance |
| Static method | static void Foo() | Không có this, gọi qua ClassName.Foo() |
| Extension method | static void Foo(this T t) | Mở rộng type có sẵn, gọi như instance method |
| Local function | void Foo() { } trong method | Chỉ dùng trong method chứa, capture variables |
| Anonymous/Delegate | Func<int,int> f = x => x*2; | Delegate, lambda |
| Expression-bodied | int 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 Funcsquare = x => x * x; square(5);