Type.GetInterfaces Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
При переопределении в производном классе получает все интерфейсы, реализованные или унаследованные текущим Type.
public:
abstract cli::array <Type ^> ^ GetInterfaces();
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.Interfaces)]
public abstract Type[] GetInterfaces();
public abstract Type[] GetInterfaces();
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.Interfaces)>]
abstract member GetInterfaces : unit -> Type[]
abstract member GetInterfaces : unit -> Type[]
Public MustOverride Function GetInterfaces () As Type()
Возвращаемое значение
Массив Type объектов, представляющих все интерфейсы, реализованные или унаследованные текущим Type.
–или–
Пустой массив типа Type, если интерфейсы не реализуются или наследуются текущим Type.
Реализации
- Атрибуты
Исключения
Вызывается статический инициализатор и вызывает исключение.
Примеры
В следующем примере возвращается тип указанного класса и отображаются все интерфейсы, реализующие или наследуемые типом. Чтобы скомпилировать пример Visual Basic, используйте следующие команды компилятора:
vbc type_getinterfaces1.vb /r:System.Web.dll /r:System.dll
using System;
using System.Collections.Generic;
public class Example
{
static void Main()
{
Console.WriteLine("\r\nInterfaces implemented by Dictionary<int, string>:\r\n");
foreach (Type tinterface in typeof(Dictionary<int, string>).GetInterfaces())
{
Console.WriteLine(tinterface.ToString());
}
//Console.ReadLine() // Uncomment this line for Visual Studio.
}
}
/* This example produces output similar to the following:
Interfaces implemented by Dictionary<int, string>:
System.Collections.Generic.IDictionary`2[System.Int32,System.String]
System.Collections.Generic.ICollection`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
System.Collection.IEnumerable
System.Collection.IDictionary
System.Collection.ICollection
System.Runtime.Serialization.ISerializable
System.Runtime.Serialization.IDeserializationCallback
*/
open System.Collections.Generic
printfn "\nInterfaces implemented by Dictionary<int, string>:\n"
for tinterface in typeof<Dictionary<int, string>>.GetInterfaces() do
printfn $"{tinterface}"
(* This example produces output similar to the following:
Interfaces implemented by Dictionary<int, string>:
System.Collections.Generic.IDictionary`2[System.Int32,System.String]
System.Collections.Generic.ICollection`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
System.Collection.IEnumerable
System.Collection.IDictionary
System.Collection.ICollection
System.Runtime.Serialization.ISerializable
System.Runtime.Serialization.IDeserializationCallback
*)
Imports System.Collections.Generic
Public Class Example
Shared Sub Main()
Console.WriteLine(vbCrLf & _
"Interfaces implemented by Dictionary(Of Integer, String):" & vbCrLf)
For Each tinterface As Type In GetType(Dictionary(Of Integer, String)).GetInterfaces()
Console.WriteLine(tinterface.ToString())
Next
'Console.ReadLine() ' Uncomment this line for Visual Studio.
End Sub
End Class
' This example produces output similar to the following:
'
'Interfaces implemented by Dictionary(Of Integer, String):
'System.Collections.Generic.IDictionary`2[System.Int32,System.String]
'System.Collections.Generic.ICollection`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
'System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
'System.Collection.IEnumerable
'System.Collection.IDictionary
'System.Collection.ICollection
'System.Runtime.Serialization.ISerializable
'System.Runtime.Serialization.IDeserializationCallback
Комментарии
В .NET 6 и более ранних версиях метод GetInterfaces не возвращает интерфейсы в определенном порядке, например в алфавитном порядке или порядке объявления. Код не должен зависеть от порядка возврата интерфейсов, так как этот порядок зависит. Однако начиная с .NET 7 порядок детерминирован на основе порядка метаданных в сборке.
Если текущий Type представляет созданный универсальный тип, этот метод возвращает Type объекты с параметрами типа, замененными соответствующими аргументами типа.
Если текущий Type представляет параметр типа в определении универсального типа или универсального метода, этот метод выполняет поиск ограничений интерфейса и любых интерфейсов, унаследованных от ограничений класса или интерфейса.