📜  C#| Type.GetInterfaces()方法

📅  最后修改于: 2021-05-30 00:16:56             🧑  作者: Mango

Type.GetInterfaces()方法用于在派生类中重写时,获取由当前Type实现或继承的所有接口。

下面的程序说明了Type.GetInterfaces()方法的用法:

范例1:

// C# program to demonstrate the
// Type.GetInterfaces() Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and intializing object of Type
        Type objType = typeof(int);
  
        // Getting interface of specified name
        // using GetField(String) Method
        Type[] minterface = objType.GetInterfaces();
  
        // Display the Result
        Console.WriteLine("Interface present in type {0}", objType);
        for (int i = 0; i < minterface.Length; i++)
            Console.WriteLine(" {0}", minterface[i]);
    }
}
输出:
Interface present in type System.Int32
 System.IFormattable
 System.IComparable
 System.IComparable`1[System.Int32]
 System.IConvertible
 System.IEquatable`1[System.Int32]

示例2:如果未定义公共字段

// C# program to demonstrate the
// Type.GetInterfaces() Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and intializing object of Type
        Type objType = typeof(string);
  
        // Getting interface of specified name
        // using GetField(String) Method
        Type[] minterface = objType.GetInterfaces();
  
        // Display the Result
        Console.WriteLine("Interface present in type {0}", objType);
        for (int i = 0; i < minterface.Length; i++)
            Console.WriteLine(" {0}", minterface[i]);
    }
}
输出:
Interface present in type System.String
 System.ICloneable
 System.Collections.Generic.IEnumerable`1[System.Char]
 System.IComparable
 System.IComparable`1[System.String]
 System.IConvertible
 System.Collections.IEnumerable
 System.IEquatable`1[System.String]

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.type.getinterfaces?view=netframework-4.8