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

Hiển thị phương thức và thuộc tính bằng Reflection trong C#

Reflection là quá trình kiểm tra siêu dữ liệu (metadata) của các kiểu, phương thức, trường trong mã tại runtime. Namespace System.Reflection cung cấp các lớp như Assembly, Type, MethodInfo, PropertyInfo, FieldInfo... để truy xuất thông tin này.

Ví dụ: Liệt kê properties và methods của TextInfo

using System;
using System.Reflection;
using System.Globalization;
using System.Text;

class Program
{
    static void Main()
    {
        TypeInfo myType = typeof(TextInfo).GetTypeInfo();
        IEnumerable<PropertyInfo> properties = myType.DeclaredProperties;
        IEnumerable<MethodInfo> methods = myType.DeclaredMethods;

        Console.WriteLine($"Type: {myType}");
        Console.WriteLine($"Properties count: {properties.Count()}");
        Console.WriteLine($"Methods count: {methods.Count()}");

        var sb = new StringBuilder();
        sb.AppendLine("=== Properties ===");
        foreach (var p in properties)
            sb.AppendLine(p.Name);

        sb.AppendLine("\n=== Methods ===");
        foreach (var m in methods)
            sb.AppendLine(m.Name);

        Console.WriteLine(sb.ToString());
        Console.ReadLine();
    }
}

Kết quả mẫu (rút gọn)

Type: System.Globalization.TextInfo
Properties count: 12
Methods count: 45

=== Properties ===
Invariant
ANSICodePage
OEMCodePage
...
IsRightToLeft

=== Methods ===
get_Invariant
get_ANSICodePage
...
ToTitleCase
AddNonLetter
...

Các lớp Reflection thường dùng

  • Assembly: Nạp và kiểm tra assembly.
  • Type / TypeInfo: Thông tin kiểu dữ liệu.
  • MethodInfo: Thông tin phương thức (tên, tham số, kiểu trả về, attribute...).
  • PropertyInfo: Thông tin thuộc tính.
  • FieldInfo: Thông tin trường (field).
  • ConstructorInfo: Thông tin constructor.
  • MemberInfo: Lớp cơ sở cho các thành viên.

Ứng dụng thực tế: Plugin system, serialization, dependency injection container, mapping object (AutoMapper), testing, dynamic proxy.