Type.GetInterface Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает определенный интерфейс, реализуемый или наследуемый текущим объектом Type.
Перегрузки
| GetInterface(String) |
Выполняет поиск интерфейса с заданным именем. |
| GetInterface(String, Boolean) |
При переопределении в производном классе ищет интерфейс с заданным именем, позволяющий определить, нужно ли выполнять поиск без учета регистра. |
GetInterface(String)
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
Выполняет поиск интерфейса с заданным именем.
public:
Type ^ GetInterface(System::String ^ name);
public:
virtual Type ^ GetInterface(System::String ^ name);
public Type? GetInterface (string name);
public Type GetInterface (string name);
member this.GetInterface : string -> Type
abstract member GetInterface : string -> Type
override this.GetInterface : string -> Type
Public Function GetInterface (name As String) As Type
Параметры
- name
- String
Строка, содержащая имя искомого интерфейса. Для универсальных интерфейсов это искаженное имя.
Возвращаемое значение
Объект, представляющий интерфейс с заданным именем, который реализуется или наследуется текущим объектом Type, если такой интерфейс существует; в противном случае — значение null.
Реализации
Исключения
name имеет значение null.
Текущий Type представляет тип, реализующий тот же универсальный интерфейс с другими аргументами типа.
Примеры
В следующем примере кода метод используется GetInterface(String) для поиска Hashtable в классе интерфейса IDeserializationCallback и перечисляет методы интерфейса .
В примере кода также демонстрируется перегрузка GetInterface(String, Boolean) метода и GetInterfaceMap метод .
int main()
{
Hashtable^ hashtableObj = gcnew Hashtable;
Type^ objType = hashtableObj->GetType();
array<MemberInfo^>^arrayMemberInfo;
array<MethodInfo^>^arrayMethodInfo;
try
{
// Get the methods implemented in 'IDeserializationCallback' interface.
arrayMethodInfo = objType->GetInterface( "IDeserializationCallback" )->GetMethods();
Console::WriteLine( "\nMethods of 'IDeserializationCallback' Interface :" );
for ( int index = 0; index < arrayMethodInfo->Length; index++ )
Console::WriteLine( arrayMethodInfo[ index ] );
// Get FullName for interface by using Ignore case search.
Console::WriteLine( "\nMethods of 'IEnumerable' Interface" );
arrayMethodInfo = objType->GetInterface( "ienumerable", true )->GetMethods();
for ( int index = 0; index < arrayMethodInfo->Length; index++ )
Console::WriteLine( arrayMethodInfo[ index ] );
//Get the Interface methods for 'IDictionary*' interface
InterfaceMapping interfaceMappingObj;
interfaceMappingObj = objType->GetInterfaceMap( IDictionary::typeid );
arrayMemberInfo = interfaceMappingObj.InterfaceMethods;
Console::WriteLine( "\nHashtable class Implements the following IDictionary Interface methods :" );
for ( int index = 0; index < arrayMemberInfo->Length; index++ )
Console::WriteLine( arrayMemberInfo[ index ] );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception : {0}", e );
}
}
public static void Main()
{
Hashtable hashtableObj = new Hashtable();
Type objType = hashtableObj.GetType();
MethodInfo[] arrayMethodInfo;
MemberInfo[] arrayMemberInfo;
try
{
// Get the methods implemented in 'IDeserializationCallback' interface.
arrayMethodInfo =objType.GetInterface("IDeserializationCallback").GetMethods();
Console.WriteLine ("\nMethods of 'IDeserializationCallback' Interface :");
foreach(MethodInfo methodInfo in arrayMethodInfo)
Console.WriteLine (methodInfo);
// Get FullName for interface by using Ignore case search.
Console.WriteLine ("\nMethods of 'IEnumerable' Interface");
arrayMethodInfo = objType.GetInterface("ienumerable",true).GetMethods();
foreach(MethodInfo methodInfo in arrayMethodInfo)
Console.WriteLine (methodInfo);
//Get the Interface methods for 'IDictionary' interface
InterfaceMapping interfaceMappingOb = objType.GetInterfaceMap(typeof(IDictionary));
arrayMemberInfo = interfaceMappingObj.InterfaceMethods;
Console.WriteLine ("\nHashtable class Implements the following IDictionary Interface methods :");
foreach(MemberInfo memberInfo in arrayMemberInfo)
Console.WriteLine (memberInfo);
}
catch (Exception e)
{
Console.WriteLine ("Exception : " + e.ToString());
}
}
let hashtableObj = Hashtable()
let objType = hashtableObj.GetType()
try
// Get the methods implemented in 'IDeserializationCallback' interface.
let arrayMethodInfo = objType.GetInterface("IDeserializationCallback").GetMethods()
printfn "\nMethods of 'IDeserializationCallback' Interface :"
for methodInfo in arrayMethodInfo do
printfn $"{methodInfo}"
// Get FullName for interface by using Ignore case search.
printfn "\nMethods of 'IEnumerable' Interface"
let arrayMethodInfo = objType.GetInterface("ienumerable",true).GetMethods()
for methodInfo in arrayMethodInfo do
printfn $"{methodInfo}"
//Get the Interface methods for 'IDictionary' interface
let interfaceMappingObj = objType.GetInterfaceMap typeof<IDictionary>
let arrayMemberInfo = interfaceMappingObj.InterfaceMethods
printfn "\nHashtable class Implements the following IDictionary Interface methods :"
for memberInfo in arrayMemberInfo do
printfn $"{memberInfo}"
with e ->
printfn $"Exception : {e}"
Public Shared Sub Main()
Dim hashtableObj As New Hashtable()
Dim objType As Type = hashtableObj.GetType()
Dim arrayMemberInfo() As MemberInfo
Dim arrayMethodInfo() As MethodInfo
Try
' Get the methods implemented in 'IDeserializationCallback' interface.
arrayMethodInfo = objType.GetInterface("IDeserializationCallback").GetMethods()
Console.WriteLine(ControlChars.Cr + "Methods of 'IDeserializationCallback' Interface :")
Dim index As Integer
For index = 0 To arrayMethodInfo.Length - 1
Console.WriteLine(arrayMethodInfo(index).ToString())
Next index
' Get FullName for interface by using Ignore case search.
Console.WriteLine(ControlChars.Cr + "Methods of 'IEnumerable' Interface")
arrayMethodInfo = objType.GetInterface("ienumerable", True).GetMethods()
For index = 0 To arrayMethodInfo.Length - 1
Console.WriteLine(arrayMethodInfo(index).ToString())
Next index
'Get the Interface methods for 'IDictionary' interface
Dim interfaceMappingObj As InterfaceMapping
interfaceMappingObj = objType.GetInterfaceMap(GetType(IDictionary))
arrayMemberInfo = interfaceMappingObj.InterfaceMethods
Console.WriteLine(ControlChars.Cr + "Hashtable class Implements the following IDictionary Interface methods :")
For index = 0 To arrayMemberInfo.Length - 1
Console.WriteLine(arrayMemberInfo(index).ToString())
Next index
Catch e As Exception
Console.WriteLine(("Exception : " + e.ToString()))
End Try
End Sub
End Class
Комментарии
В поиске name учитывается регистр.
Если текущий Type представляет сконструированный универсальный тип, этот метод возвращает Type с параметрами типа, замененными соответствующими аргументами типа.
Если текущий Type объект представляет параметр типа в определении универсального типа или универсального метода, этот метод выполняет поиск ограничений интерфейса и интерфейсов, унаследованных от ограничений класса или интерфейса.
Примечание
Для универсальных интерфейсов name параметр представляет собой искаженное имя, оканчивающееся серьезным акцентом (') и числом параметров типа. Это верно как для определений универсальных интерфейсов, так и для сконструированных универсальных интерфейсов. Например, чтобы найти IExample<T> (IExample(Of T) в Visual Basic) или IExample<string> (IExample(Of String) в Visual Basic), выполните поиск по запросу "IExample`1".
См. также раздел
Применяется к
GetInterface(String, Boolean)
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
При переопределении в производном классе ищет интерфейс с заданным именем, позволяющий определить, нужно ли выполнять поиск без учета регистра.
public:
abstract Type ^ GetInterface(System::String ^ name, bool ignoreCase);
public abstract Type? GetInterface (string name, bool ignoreCase);
public abstract Type GetInterface (string name, bool ignoreCase);
abstract member GetInterface : string * bool -> Type
Public MustOverride Function GetInterface (name As String, ignoreCase As Boolean) As Type
Параметры
- name
- String
Строка, содержащая имя искомого интерфейса. Для универсальных интерфейсов это искаженное имя.
- ignoreCase
- Boolean
Значение true, чтобы игнорировать регистр той части параметра name, в которой задается простое имя интерфейса (регистр части, соответствующей пространству имен, должен быть надлежащим образом соблюден).
-или-
Значение false, для поиска с учетом регистра всех частей параметра name.
Возвращаемое значение
Объект, представляющий интерфейс с заданным именем, который реализуется или наследуется текущим объектом Type, если такой интерфейс существует; в противном случае — значение null.
Реализации
Исключения
name имеет значение null.
Текущий Type представляет тип, реализующий тот же универсальный интерфейс с другими аргументами типа.
Примеры
В следующем примере кода метод используется GetInterface(String, Boolean) для IEnumerable выполнения поиска интерфейса без учета регистра в Hashtable классе .
В примере кода также демонстрируется перегрузка GetInterface(String) метода и GetInterfaceMap метод .
int main()
{
Hashtable^ hashtableObj = gcnew Hashtable;
Type^ objType = hashtableObj->GetType();
array<MemberInfo^>^arrayMemberInfo;
array<MethodInfo^>^arrayMethodInfo;
try
{
// Get the methods implemented in 'IDeserializationCallback' interface.
arrayMethodInfo = objType->GetInterface( "IDeserializationCallback" )->GetMethods();
Console::WriteLine( "\nMethods of 'IDeserializationCallback' Interface :" );
for ( int index = 0; index < arrayMethodInfo->Length; index++ )
Console::WriteLine( arrayMethodInfo[ index ] );
// Get FullName for interface by using Ignore case search.
Console::WriteLine( "\nMethods of 'IEnumerable' Interface" );
arrayMethodInfo = objType->GetInterface( "ienumerable", true )->GetMethods();
for ( int index = 0; index < arrayMethodInfo->Length; index++ )
Console::WriteLine( arrayMethodInfo[ index ] );
//Get the Interface methods for 'IDictionary*' interface
InterfaceMapping interfaceMappingObj;
interfaceMappingObj = objType->GetInterfaceMap( IDictionary::typeid );
arrayMemberInfo = interfaceMappingObj.InterfaceMethods;
Console::WriteLine( "\nHashtable class Implements the following IDictionary Interface methods :" );
for ( int index = 0; index < arrayMemberInfo->Length; index++ )
Console::WriteLine( arrayMemberInfo[ index ] );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception : {0}", e );
}
}
public static void Main()
{
Hashtable hashtableObj = new Hashtable();
Type objType = hashtableObj.GetType();
MethodInfo[] arrayMethodInfo;
MemberInfo[] arrayMemberInfo;
try
{
// Get the methods implemented in 'IDeserializationCallback' interface.
arrayMethodInfo =objType.GetInterface("IDeserializationCallback").GetMethods();
Console.WriteLine ("\nMethods of 'IDeserializationCallback' Interface :");
foreach(MethodInfo methodInfo in arrayMethodInfo)
Console.WriteLine (methodInfo);
// Get FullName for interface by using Ignore case search.
Console.WriteLine ("\nMethods of 'IEnumerable' Interface");
arrayMethodInfo = objType.GetInterface("ienumerable",true).GetMethods();
foreach(MethodInfo methodInfo in arrayMethodInfo)
Console.WriteLine (methodInfo);
//Get the Interface methods for 'IDictionary' interface
InterfaceMapping interfaceMappingOb = objType.GetInterfaceMap(typeof(IDictionary));
arrayMemberInfo = interfaceMappingObj.InterfaceMethods;
Console.WriteLine ("\nHashtable class Implements the following IDictionary Interface methods :");
foreach(MemberInfo memberInfo in arrayMemberInfo)
Console.WriteLine (memberInfo);
}
catch (Exception e)
{
Console.WriteLine ("Exception : " + e.ToString());
}
}
let hashtableObj = Hashtable()
let objType = hashtableObj.GetType()
try
// Get the methods implemented in 'IDeserializationCallback' interface.
let arrayMethodInfo = objType.GetInterface("IDeserializationCallback").GetMethods()
printfn "\nMethods of 'IDeserializationCallback' Interface :"
for methodInfo in arrayMethodInfo do
printfn $"{methodInfo}"
// Get FullName for interface by using Ignore case search.
printfn "\nMethods of 'IEnumerable' Interface"
let arrayMethodInfo = objType.GetInterface("ienumerable",true).GetMethods()
for methodInfo in arrayMethodInfo do
printfn $"{methodInfo}"
//Get the Interface methods for 'IDictionary' interface
let interfaceMappingObj = objType.GetInterfaceMap typeof<IDictionary>
let arrayMemberInfo = interfaceMappingObj.InterfaceMethods
printfn "\nHashtable class Implements the following IDictionary Interface methods :"
for memberInfo in arrayMemberInfo do
printfn $"{memberInfo}"
with e ->
printfn $"Exception : {e}"
Public Shared Sub Main()
Dim hashtableObj As New Hashtable()
Dim objType As Type = hashtableObj.GetType()
Dim arrayMemberInfo() As MemberInfo
Dim arrayMethodInfo() As MethodInfo
Try
' Get the methods implemented in 'IDeserializationCallback' interface.
arrayMethodInfo = objType.GetInterface("IDeserializationCallback").GetMethods()
Console.WriteLine(ControlChars.Cr + "Methods of 'IDeserializationCallback' Interface :")
Dim index As Integer
For index = 0 To arrayMethodInfo.Length - 1
Console.WriteLine(arrayMethodInfo(index).ToString())
Next index
' Get FullName for interface by using Ignore case search.
Console.WriteLine(ControlChars.Cr + "Methods of 'IEnumerable' Interface")
arrayMethodInfo = objType.GetInterface("ienumerable", True).GetMethods()
For index = 0 To arrayMethodInfo.Length - 1
Console.WriteLine(arrayMethodInfo(index).ToString())
Next index
'Get the Interface methods for 'IDictionary' interface
Dim interfaceMappingObj As InterfaceMapping
interfaceMappingObj = objType.GetInterfaceMap(GetType(IDictionary))
arrayMemberInfo = interfaceMappingObj.InterfaceMethods
Console.WriteLine(ControlChars.Cr + "Hashtable class Implements the following IDictionary Interface methods :")
For index = 0 To arrayMemberInfo.Length - 1
Console.WriteLine(arrayMemberInfo(index).ToString())
Next index
Catch e As Exception
Console.WriteLine(("Exception : " + e.ToString()))
End Try
End Sub
End Class
Комментарии
Параметр ignoreCase применяется только к простому имени интерфейса, но не к пространству имен. Часть name , указывающая пространство имен, должна иметь правильный регистр, иначе интерфейс не будет найден. Например, строка "System.icomparable" находит IComparable интерфейс, а строка "system.icomparable" — нет.
Если текущий Type представляет сконструированный универсальный тип, этот метод возвращает Type с параметрами типа, замененными соответствующими аргументами типа.
Если текущий Type объект представляет параметр типа в определении универсального типа или универсального метода, этот метод выполняет поиск ограничений интерфейса и интерфейсов, унаследованных от ограничений класса или интерфейса.
Примечание
Для универсальных интерфейсов name параметр представляет собой искаженное имя, оканчивающееся серьезным акцентом (') и числом параметров типа. Это верно как для определений универсальных интерфейсов, так и для сконструированных универсальных интерфейсов. Например, чтобы найти IExample<T> (IExample(Of T) в Visual Basic) или IExample<string> (IExample(Of String) в Visual Basic), выполните поиск по запросу "IExample`1".