Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การดึงอินเทอร์เฟซเฉพาะที่ Type ปัจจุบันนำมาหรือสืบทอดใน C#

ภาพรวม

เมธอด Type.GetInterface(string name, bool ignoreCase) คืน Type ของอินเทอร์เฟซที่มีชื่อตรงตามที่ระบุ (คืน null หากไม่พบ)

ตัวอย่างที่ 1: หา IFormattable ของ double

using System;

public class Demo
{
    public static void Main()
    {
        Type type = typeof(double);
        Type myInterface = type.GetInterface("IFormattable");
        Console.WriteLine("Interface = " + myInterface);
    }
}

ผลลัพธ์

Interface = System.IFormattable

ตัวอย่างที่ 2: หา IFormattable ของ float พร้อม ignoreCase

using System;

public class Demo
{
    public static void Main()
    {
        Type type = typeof(float);
        Type myInterface = type.GetInterface("IFormattable", true);
        Console.WriteLine("Interface = " + myInterface);
    }
}

ผลลัพธ์

Interface = System.IFormattable

สรุป

  • GetInterface คืน Type เดียว ไม่ใช่อาร์เรย์
  • พารามิเตอร์ ignoreCase ควบคุมการเปรียบเทียบชื่อตัวพิมพ์เล็ก/ใหญ่
  • หากไม่พบ คืน null (ไม่โยน exception)