Assembly.GetType Метод
Определение
Перегрузки
GetType(String, Boolean, Boolean) |
Возвращает объект Type с заданным именем в экземпляре сборки, с возможностями игнорировать регистр и вызвать исключение, если тип не найден.Gets the Type object with the specified name in the assembly instance, with the options of ignoring the case, and of throwing an exception if the type is not found. |
GetType(String, Boolean) |
Возвращает объект Type с заданным именем в экземпляре сборки и может вызывать исключение, если тип не найден.Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found. |
GetType(String) |
Возвращает объект Type с указанным именем в экземпляре сборки.Gets the Type object with the specified name in the assembly instance. |
GetType() |
GetType(String, Boolean, Boolean)
Возвращает объект Type с заданным именем в экземпляре сборки, с возможностями игнорировать регистр и вызвать исключение, если тип не найден.Gets the Type object with the specified name in the assembly instance, with the options of ignoring the case, and of throwing an exception if the type is not found.
public:
virtual Type ^ GetType(System::String ^ name, bool throwOnError, bool ignoreCase);
public virtual Type GetType (string name, bool throwOnError, bool ignoreCase);
public virtual Type? GetType (string name, bool throwOnError, bool ignoreCase);
public Type GetType (string name, bool throwOnError, bool ignoreCase);
override this.GetType : string * bool * bool -> Type
Public Overridable Function GetType (name As String, throwOnError As Boolean, ignoreCase As Boolean) As Type
Public Function GetType (name As String, throwOnError As Boolean, ignoreCase As Boolean) As Type
Параметры
- name
- String
Полное имя типа.The full name of the type.
- throwOnError
- Boolean
Значение true
для создания исключения, если тип не найден, в обратном случае — значение false
, в результате чего будет возвращено значение null
.true
to throw an exception if the type is not found; false
to return null
.
- ignoreCase
- Boolean
Значение true
, чтобы игнорировать регистр имени типа, в обратном случае — значение false
.true
to ignore the case of the type name; otherwise, false
.
Возвращаемое значение
Объект, представляющий указанный класс.An object that represents the specified class.
Реализации
Исключения
name
недопустим.name
is invalid.
-или--or-
Длина name
превышает 1024 символа.The length of name
exceeds 1024 characters.
name
имеет значение null
.name
is null
.
throwOnError
является true
, не удается найти тип.throwOnError
is true
, and the type cannot be found.
Для name
требуется зависимая сборка, которую не удалось найти.name
requires a dependent assembly that could not be found.
Для name
требуется зависимая сборка, которая была найдена, но ее не удалось загрузить.name
requires a dependent assembly that was found but could not be loaded.
-или--or-
Текущая сборка была загружена в контекст только для отражения, а для name
требуется зависимая сборка, которая не была предварительно загружена.The current assembly was loaded into the reflection-only context, and name
requires a dependent assembly that was not preloaded.
Для name
требуется зависимая сборка, однако файл не является допустимой сборкой.name
requires a dependent assembly, but the file is not a valid assembly.
-или--or-
Для name
требуется зависимая сборка, которая была скомпилирована для версии среды выполнения более поздней, чем текущая загруженная версия.name
requires a dependent assembly which was compiled for a version of the runtime later than the currently loaded version.
Комментарии
Этот метод выполняет поиск только в текущем экземпляре сборки.This method only searches the current assembly instance. name
Параметр включает пространство имен, но не сборку.The name
parameter includes the namespace but not the assembly. Чтобы найти другие сборки для типа, используйте Type.GetType(String) перегрузку метода, которая при необходимости может включать отображаемое имя сборки как часть имени типа.To search other assemblies for a type, use the Type.GetType(String) method overload, which can optionally include an assembly display name as part of the type name.
Примечание
Если тип был перенаправлен другой сборке, он по-прежнему возвращается этим методом.If the type has been forwarded to another assembly, it is still returned by this method. Дополнительные сведения о пересылке типов см. в разделе Пересылка типов в среде CLR.For information on type forwarding, see Type Forwarding in the Common Language Runtime.
throwOnError
Параметр влияет только на то, что происходит, если тип не найден.The throwOnError
parameter only affects what happens when the type is not found. Он не влияет на другие исключения, которые могут возникать.It does not affect any other exceptions that might be thrown. В частности, если тип найден, но не может быть загружен, TypeLoadException может возникнуть исключение, даже если throwOnError
имеет значение false
.In particular, if the type is found but cannot be loaded, TypeLoadException can be thrown even if throwOnError
is false
.
Применяется к
GetType(String, Boolean)
public:
virtual Type ^ GetType(System::String ^ name, bool throwOnError);
public virtual Type? GetType (string name, bool throwOnError);
public virtual Type GetType (string name, bool throwOnError);
override this.GetType : string * bool -> Type
Public Overridable Function GetType (name As String, throwOnError As Boolean) As Type
Параметры
- name
- String
Полное имя типа.The full name of the type.
- throwOnError
- Boolean
Значение true
для создания исключения, если тип не найден, в обратном случае — значение false
, в результате чего будет возвращено значение null
.true
to throw an exception if the type is not found; false
to return null
.
Возвращаемое значение
Объект, представляющий указанный класс.An object that represents the specified class.
Реализации
Исключения
name
недопустим.name
is invalid.
-или--or-
Длина name
превышает 1024 символа.The length of name
exceeds 1024 characters.
name
имеет значение null
.name
is null
.
throwOnError
является true
, не удается найти тип.throwOnError
is true
, and the type cannot be found.
Для name
требуется зависимая сборка, которую не удалось найти.name
requires a dependent assembly that could not be found.
Для name
требуется зависимая сборка, которая была найдена, но ее не удалось загрузить.name
requires a dependent assembly that was found but could not be loaded.
-или--or-
Текущая сборка была загружена в контекст только для отражения, а для name
требуется зависимая сборка, которая не была предварительно загружена.The current assembly was loaded into the reflection-only context, and name
requires a dependent assembly that was not preloaded.
Для name
требуется зависимая сборка, однако файл не является допустимой сборкой.name
requires a dependent assembly, but the file is not a valid assembly.
-или--or-
Для name
требуется зависимая сборка, которая была скомпилирована для версии среды выполнения более поздней, чем текущая загруженная версия.name
requires a dependent assembly which was compiled for a version of the runtime later than the currently loaded version.
Комментарии
Этот метод выполняет поиск только в текущем экземпляре сборки.This method only searches the current assembly instance. name
Параметр включает пространство имен, но не сборку.The name
parameter includes the namespace but not the assembly. Чтобы найти другие сборки для типа, используйте Type.GetType(String) перегрузку метода, которая при необходимости может включать отображаемое имя сборки как часть имени типа.To search other assemblies for a type, use the Type.GetType(String) method overload, which can optionally include an assembly display name as part of the type name.
Примечание
Если тип был перенаправлен другой сборке, он по-прежнему возвращается этим методом.If the type has been forwarded to another assembly, it is still returned by this method. Дополнительные сведения о пересылке типов см. в разделе Пересылка типов в среде CLR.For information on type forwarding, see Type Forwarding in the Common Language Runtime.
throwOnError
Параметр влияет только на то, что происходит, если тип не найден.The throwOnError
parameter only affects what happens when the type is not found. Он не влияет на другие исключения, которые могут возникать.It does not affect any other exceptions that might be thrown. В частности, если тип найден, но не может быть загружен, TypeLoadException может возникнуть исключение, даже если throwOnError
имеет значение false
.In particular, if the type is found but cannot be loaded, TypeLoadException can be thrown even if throwOnError
is false
.
Применяется к
GetType(String)
public:
virtual Type ^ GetType(System::String ^ name);
public virtual Type GetType (string name);
public virtual Type? GetType (string name);
override this.GetType : string -> Type
Public Overridable Function GetType (name As String) As Type
Параметры
- name
- String
Полное имя типа.The full name of the type.
Возвращаемое значение
Объект, представляющий указанный класс, или null
, если класс не найден.An object that represents the specified class, or null
if the class is not found.
Реализации
Исключения
name
недопустим.name
is invalid.
name
имеет значение null
.name
is null
.
Для name
требуется зависимая сборка, которую не удалось найти.name
requires a dependent assembly that could not be found.
Вместо этого в .NET для приложений Магазина Windows или в переносимой библиотеке классов перехватите исключение базового класса IOException.In the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, IOException, instead.
name
требуется зависимая сборка, которая была найдена, но ее не удалось загрузить.
name
requires a dependent assembly that was found but could not be loaded.
-или--or-
Текущая сборка была загружена в контекст только для отражения, а для name
требуется зависимая сборка, которая не была предварительно загружена.The current assembly was loaded into the reflection-only context, and name
requires a dependent assembly that was not preloaded.
Для name
требуется зависимая сборка, однако файл не является допустимой сборкой.name
requires a dependent assembly, but the file is not a valid assembly.
-или--or-
Для name
требуется зависимая сборка, которая была скомпилирована для версии среды выполнения более поздней, чем текущая загруженная версия.name
requires a dependent assembly which was compiled for a version of the runtime later than the currently loaded version.
Примеры
В следующем примере определяется абстрактный MeansOfTransportation
класс в Transportation
пространстве имен.The following example defines an abstract MeansOfTransportation
class in the Transportation
namespace. Он вызывает GetType(String) метод для получения своего Type объекта, вызывает Type.GetProperties метод для получения массива PropertyInfo объектов, представляющих свойства типа, а затем отображает сведения о абстрактных свойствах типа.It calls the GetType(String) method to retrieve its Type object, calls the Type.GetProperties method to get an array of PropertyInfo objects that represent the type's properties, and then displays information on the type's abstract properties. Обратите внимание, что вызов GetType(String) метода использует полное имя типа (то есть его пространство имен и имя типа).Note that the call to the GetType(String) method uses the type's fully qualified name (that is, its namespace along with its type name).
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
Assembly assem = typeof(Example).Assembly;
Type t = assem.GetType("Transportation.MeansOfTransportation");
if (t != null)
{
Console.WriteLine($"Virtual properties in type {t.FullName}:");
PropertyInfo[] props = t.GetProperties();
int nVirtual = 0;
for (int ctr = 0; ctr < props.Length; ctr++)
{
if (props[ctr].GetMethod.IsVirtual)
{
Console.WriteLine($" {props[ctr].Name} (type {props[ctr].PropertyType.FullName})");
nVirtual++;
}
}
if (nVirtual == 0)
Console.WriteLine(" No virtual properties");
}
}
}
namespace Transportation
{
public abstract class MeansOfTransportation
{
abstract public bool HasWheels { get; set; }
abstract public int Wheels { get; set; }
abstract public bool ConsumesFuel { get; set; }
abstract public bool Living { get; set; }
}
}
// The example displays the following output:
// Virtual properties in type Transportation.MeansOfTransportation:
// HasWheels (type System.Boolean)
// Wheels (type System.Int32)
// ConsumesFuel (type System.Boolean)
// Living (type System.Boolean)
Imports System.Reflection
Module Example
Public Sub Main()
Dim assem As Assembly = GetType(Example).Assembly
Dim t As Type = assem.GetType("Transportation.MeansOfTransportation")
If Not t Is Nothing Then
Console.WriteLine("Virtual properties in type {0}:",
t.FullName)
Dim props() As PropertyInfo = t.GetProperties()
Dim nVirtual As Integer = 0
For ctr As Integer = 0 To props.Length - 1
If props(ctr).GetMethod.IsVirtual Then
Console.WriteLine(" {0} (type {1})",
props(ctr).Name,
props(ctr).PropertyType.FullName)
nVirtual += 1
End If
Next
If nVirtual = 0 Then
Console.WriteLine(" No virtual properties")
End If
End If
End Sub
End Module
Namespace Transportation
Public MustInherit Class MeansOfTransportation
Public MustOverride Property HasWheels As Boolean
Public MustOverride Property Wheels As Integer
Public MustOverride Property ConsumesFuel As Boolean
Public MustOverride Property Living As Boolean
End Class
End Namespace
' The example displays the following output:
' Virtual properties in type Transportation.MeansOfTransportation:
' HasWheels (type System.Boolean)
' Wheels (type System.Int32)
' ConsumesFuel (type System.Boolean)
' Living (type System.Boolean)
Комментарии
Этот метод выполняет поиск только в текущем экземпляре сборки.This method only searches the current assembly instance. name
Параметр включает пространство имен, но не сборку.The name
parameter includes the namespace but not the assembly. Чтобы найти другие сборки для типа, используйте Type.GetType(String) перегрузку метода, которая при необходимости может включать отображаемое имя сборки как часть имени типа.To search other assemblies for a type, use the Type.GetType(String) method overload, which can optionally include an assembly display name as part of the type name.
Примечание
Если тип был перенаправлен другой сборке, он по-прежнему возвращается этим методом.If the type has been forwarded to another assembly, it is still returned by this method. Дополнительные сведения о пересылке типов см. в разделе Пересылка типов в среде CLR.For information on type forwarding, see Type Forwarding in the Common Language Runtime.