獲取當前型別在 C# 中實現或繼承的所有介面


如果要獲取當前 Type 實現或繼承的所有介面,可以編寫如下程式碼 −

示例

 線上演示

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("All the Interfaces...");
      for (int i = 0; i < myInterfaces.Length; i++)
      Console.WriteLine(""+myInterfaces[i]);
   }
}

輸出

該程式碼將生成以下輸出 −

Interface = System.IFormattable
All the Interfaces...
System.IComparable
System.IFormattable
System.IConvertible
System.IComparable`1[System.Single]
System.IEquatable`1[System.Single]

我們再看一個示例 −

示例

 線上演示

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("All the Interfaces...");
      for (int i = 0; i < myInterfaces.Length; i++)
      Console.WriteLine(""+myInterfaces[i]);
   }
}

輸出

該程式碼將生成以下輸出 −

Interface = System.IFormattable
All the Interfaces...
System.IComparable
System.IFormattable
System.IConvertible
System.IComparable`1[System.Int32]
System.IEquatable`1[System.Int32]

更新於: 11-Dec-2019

423 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.