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

Lấy tất cả interface được triển khai bởi Type hiện tại C#

Ví dụ 1: Kiểu float

using System;

public class Demo {
    public static void Main() {
        Type type = typeof(float);
        Type myInterface = type.GetInterface("IFormattable", true);
        Type[] myInterfaces = type.GetInterfaces();
        
        Console.WriteLine("Interface = " + myInterface);
        Console.WriteLine("Tất cả Interface...");
        for (int i = 0; i < myInterfaces.Length; i++)
            Console.WriteLine("" + myInterfaces[i]);
    }
}

Kết quả

Interface = System.IFormattable
Tất cả Interface...
System.IComparable
System.IFormattable
System.IConvertible
System.IComparable`1[System.Single]
System.IEquatable`1[System.Single]

Ví dụ 2: Kiểu int

using System;

public class Demo {
    public static void Main() {
        Type type = typeof(int);
        Type myInterface = type.GetInterface("IFormattable");
        Type[] myInterfaces = type.GetInterfaces();
        
        Console.WriteLine("Interface = " + myInterface);
        Console.WriteLine("Tất cả Interface...");
        for (int i = 0; i < myInterfaces.Length; i++)
            Console.WriteLine("" + myInterfaces[i]);
    }
}

Kết quả

Interface = System.IFormattable
Tất cả Interface...
System.IComparable
System.IFormattable
System.IConvertible
System.IComparable`1[System.Int32]
System.IEquatable`1[System.Int32]

Giải thích: GetInterfaces() trả về mảng tất cả interface mà kiểu triển khai (kể cả generic). GetInterface("Tên") tìm interface cụ thể.