Type.GetConstructor Метод
Определение
Перегрузки
GetConstructor(Type[]) |
Выполняет поиск открытого конструктора экземпляра, параметры которого соответствуют типам, содержащимся в указанном массиве.Searches for a public instance constructor whose parameters match the types in the specified array. |
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) |
Выполняет поиск конструктора, параметры которого соответствуют указанным типам аргументов и модификаторам, используя заданные ограничения привязки.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
Выполняет поиск конструктора с параметрами, соответствующими указанным модификаторам и типам аргументов, с учетом заданных ограничений по привязке и соглашений о вызовах.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetConstructor(Type[])
Выполняет поиск открытого конструктора экземпляра, параметры которого соответствуют типам, содержащимся в указанном массиве.Searches for a public instance constructor whose parameters match the types in the specified array.
public:
System::Reflection::ConstructorInfo ^ GetConstructor(cli::array <Type ^> ^ types);
public:
virtual System::Reflection::ConstructorInfo ^ GetConstructor(cli::array <Type ^> ^ types);
public System.Reflection.ConstructorInfo? GetConstructor (Type[] types);
public System.Reflection.ConstructorInfo GetConstructor (Type[] types);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor (Type[] types);
member this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : Type[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : Type[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (types As Type()) As ConstructorInfo
Параметры
- types
- Type[]
Массив объектов Type, предоставляющих число, порядок и тип параметров нужного конструктора.An array of Type objects representing the number, order, and type of the parameters for the desired constructor.
- или --or-
Пустой массив объектов Type для получения конструктора, не имеющего параметров.An empty array of Type objects, to get a constructor that takes no parameters. Подобный пустой массив предоставляется полем static
с описателем EmptyTypes.Such an empty array is provided by the static
field EmptyTypes.
Возвращаемое значение
Объект, представляющий открытый конструктор экземпляра, параметры которого соответствуют типам, указанным в массиве типов параметров, если такой конструктор найден; в противном случае — null
.An object representing the public instance constructor whose parameters match the types in the parameter type array, if found; otherwise, null
.
Реализации
- Атрибуты
Исключения
types
имеет значение null
.types
is null
.
- или --or-
Один из элементов в types
имеет значение null
.One of the elements in types
is null
.
Массив types
является многомерным.types
is multidimensional.
Примеры
Следующий пример получает тип MyClass
, возвращает ConstructorInfo объект и отображает сигнатуру конструктора.The following example obtains the type of MyClass
, gets the ConstructorInfo object, and displays the constructor signature.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
MyClass1(){}
MyClass1( int i ){}
};
int main()
{
try
{
Type^ myType = MyClass1::typeid;
array<Type^>^types = gcnew array<Type^>(1);
types[ 0 ] = int::typeid;
// Get the constructor that takes an integer as a parameter.
ConstructorInfo^ constructorInfoObj = myType->GetConstructor( types );
if ( constructorInfoObj != nullptr )
{
Console::WriteLine( "The constructor of MyClass1 that takes an integer as a parameter is: " );
Console::WriteLine( constructorInfoObj );
}
else
{
Console::WriteLine( "The constructor of MyClass1 that takes an integer as a parameter is not available." );
}
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception caught." );
Console::WriteLine( "Source: {0}", e->Source );
Console::WriteLine( "Message: {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
public class MyClass1
{
public MyClass1(){}
public MyClass1(int i){}
public static void Main()
{
try
{
Type myType = typeof(MyClass1);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the constructor that takes an integer as a parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(types);
if (constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass1 that takes an " +
"integer as a parameter is: ");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of MyClass1 that takes an integer " +
"as a parameter is not available.");
}
}
catch(Exception e)
{
Console.WriteLine("Exception caught.");
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("Message: " + e.Message);
}
}
}
Imports System.Reflection
Imports System.Security
Public Class MyClass1
Public Sub New()
End Sub
Public Sub New(ByVal i As Integer)
End Sub
Public Shared Sub Main()
Try
Dim myType As Type = GetType(MyClass1)
Dim types(0) As Type
types(0) = GetType(Int32)
' Get the constructor that takes an integer as a parameter.
Dim constructorInfoObj As ConstructorInfo = myType.GetConstructor(types)
If Not (constructorInfoObj Is Nothing) Then
Console.WriteLine("The constructor of MyClass that takes an integer as a parameter is: ")
Console.WriteLine(constructorInfoObj.ToString())
Else
Console.WriteLine("The constructor of MyClass that takes no " + "parameters is not available.")
End If
Catch e As Exception
Console.WriteLine("Exception caught.")
Console.WriteLine(("Source: " + e.Source))
Console.WriteLine(("Message: " + e.Message))
End Try
End Sub
End Class
Комментарии
Эта перегрузка метода выполняет поиск конструкторов открытых экземпляров и не может использоваться для получения инициализатора класса (статический конструктор).This method overload looks for public instance constructors and cannot be used to obtain a class initializer (static constructor). Чтобы получить инициализатор класса, используйте перегрузку, которая принимает BindingFlags , и укажите BindingFlags.Static | BindingFlags.NonPublic ( BindingFlags.Static Or
BindingFlags.NonPublic в Visual Basic).To get a class initializer, use an overload that takes BindingFlags, and specify BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOr
BindingFlags.NonPublic in Visual Basic). Можно также получить инициализатор класса с помощью TypeInitializer Свойства.You can also get the class initializer using the TypeInitializer property.
Если запрашиваемый конструктор не является открытым, этот метод возвращает null
.If the requested constructor is non-public, this method returns null
.
Примечание
Нельзя опустить параметры при поиске конструкторов и методов.You cannot omit parameters when looking up constructors and methods. При вызове можно опустить только параметры.You can only omit parameters when invoking.
Если текущий объект Type представляет сконструированный универсальный тип, этот метод возвращает объект ConstructorInfo с параметрами типа, замененными соответствующими аргументами типа.If the current Type represents a constructed generic type, this method returns the ConstructorInfo with the type parameters replaced by the appropriate type arguments. Если Current Type представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращает значение null
.If the current Type represents a type parameter in the definition of a generic type or generic method, this method always returns null
.
См. также раздел
- ConstructorInfo
- DefaultBinder
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Применяется к
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])
Выполняет поиск конструктора, параметры которого соответствуют указанным типам аргументов и модификаторам, используя заданные ограничения привязки.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints.
public:
System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
virtual System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.ConstructorInfo? GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.ConstructorInfo GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, binder As Binder, types As Type(), modifiers As ParameterModifier()) As ConstructorInfo
Параметры
- bindingAttr
- BindingFlags
Побитовое сочетание значений перечисления, указывающих способ проведения поиска.A bitwise combination of the enumeration values that specify how the search is conducted.
- или --or-
Default для возврата null
.Default to return null
.
- binder
- Binder
Объект, определяющий набор свойств и разрешающий привязку, что может включать выбор перегруженных методов, приведение типов аргументов и вызов члена с помощью отражения.An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.
- или --or-
Пустая ссылка (Nothing
в Visual Basic) для использования свойства DefaultBinder.A null reference (Nothing
in Visual Basic), to use the DefaultBinder.
- types
- Type[]
Массив объектов Type, предоставляющий число, порядок и тип параметров, извлекаемых конструктором.An array of Type objects representing the number, order, and type of the parameters for the constructor to get.
- или --or- Пустой массив объектов типа Type (то есть Type[] types = new Type[0]), если требуется получить конструктор, который не имеет параметров.An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
- или --or- EmptyTypes.EmptyTypes.
- modifiers
- ParameterModifier[]
Массив объектов ParameterModifier, представляющих атрибуты, связанные с соответствующим элементом в массиве типов параметра.An array of ParameterModifier objects representing the attributes associated with the corresponding element in the parameter type array. Связыватель по умолчанию не обрабатывает этот параметр.The default binder does not process this parameter.
Возвращаемое значение
Если поиск выполнен удачно, возвращается объект ConstructorInfo, представляющий конструктор, который соответствует указанным требованиям; в противном случае возвращается значение null
.A ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null
.
Реализации
- Атрибуты
Исключения
types
имеет значение null
.types
is null
.
- или --or-
Один из элементов в types
имеет значение null
.One of the elements in types
is null
.
Массив types
является многомерным.types
is multidimensional.
- или --or-
Массив modifiers
является многомерным.modifiers
is multidimensional.
- или --or-
types
и modifiers
имеют разную длину.types
and modifiers
do not have the same length.
Примеры
Следующий пример получает тип MyClass
, возвращает ConstructorInfo объект и отображает сигнатуру конструктора.The following example obtains the type of MyClass
, gets the ConstructorInfo object, and displays the constructor signature.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
MyClass1( int i ){}
};
int main()
{
try
{
Type^ myType = MyClass1::typeid;
array<Type^>^types = gcnew array<Type^>(1);
types[ 0 ] = int::typeid;
// Get the constructor that is public and takes an integer parameter.
ConstructorInfo^ constructorInfoObj = myType->GetConstructor( static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public), nullptr, types, nullptr );
if ( constructorInfoObj != nullptr )
{
Console::WriteLine( "The constructor of MyClass1 that is public and takes an integer as a parameter is:" );
Console::WriteLine( constructorInfoObj );
}
else
{
Console::WriteLine( "The constructor of the MyClass1 that is public and takes an integer as a parameter is not available." );
}
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "ArgumentNullException: {0}", e->Message );
}
catch ( ArgumentException^ e )
{
Console::WriteLine( "ArgumentException: {0}", e->Message );
}
catch ( SecurityException^ e )
{
Console::WriteLine( "SecurityException: {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
public class MyClass1
{
public MyClass1(int i){}
public static void Main()
{
try
{
Type myType = typeof(MyClass1);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the constructor that is public and takes an integer parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public, null, types, null);
if (constructorInfoObj != null )
{
Console.WriteLine("The constructor of MyClass1 that is public " +
"and takes an integer as a parameter is:");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of the MyClass1 that is public " +
"and takes an integer as a parameter is not available.");
}
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
catch(ArgumentException e)
{
Console.WriteLine("ArgumentException: " + e.Message);
}
catch(SecurityException e)
{
Console.WriteLine("SecurityException: " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
Imports System.Reflection
Imports System.Security
Public Class MyClass1
Public Sub New(ByVal i As Integer)
End Sub
Public Shared Sub Main()
Try
Dim myType As Type = GetType(MyClass1)
Dim types(0) As Type
types(0) = GetType(Integer)
' Get the constructor that is public and takes an integer parameter.
Dim constructorInfoObj As ConstructorInfo = _
myType.GetConstructor(BindingFlags.Instance Or _
BindingFlags.Public, Nothing, types, Nothing)
If Not (constructorInfoObj Is Nothing) Then
Console.WriteLine("The constructor of MyClass1 that is " + _
"public and takes an integer as a parameter is ")
Console.WriteLine(constructorInfoObj.ToString())
Else
Console.WriteLine("The constructor of MyClass1 that is " + _
"public and takes an integer as a parameter is not available.")
End If
Catch e As ArgumentNullException
Console.WriteLine("ArgumentNullException: " + e.Message)
Catch e As ArgumentException
Console.WriteLine("ArgumentException: " + e.Message)
Catch e As SecurityException
Console.WriteLine("SecurityException: " + e.Message)
Catch e As Exception
Console.WriteLine("Exception: " + e.Message)
End Try
End Sub
End Class
Комментарии
Если точное соответствие не существует, binder
будет предпринята попытка привести типы параметров, заданные в types
массиве, для выбора совпадения.If an exact match does not exist, the binder
will attempt to coerce the parameter types specified in the types
array in order to select a match. Если binder
не удается выбрать соответствие, null
возвращается значение.If the binder
is unable to select a match, then null
is returned.
BindingFlagsДля определения конструкторов, включаемых в поиск, можно использовать следующие флаги фильтра:The following BindingFlags filter flags can be used to define which constructors to include in the search:
Необходимо указать или,
BindingFlags.Instance
BindingFlags.Static
чтобы получить возвращаемое значение.You must specify eitherBindingFlags.Instance
orBindingFlags.Static
in order to get a return.Укажите
BindingFlags.Public
, чтобы включить в поиск открытые конструкторы.SpecifyBindingFlags.Public
to include public constructors in the search.Укажите
BindingFlags.NonPublic
для включения в поиск неоткрытых конструкторов (т. е. закрытых, внутренних и защищенных конструкторов).SpecifyBindingFlags.NonPublic
to include non-public constructors (that is, private, internal, and protected constructors) in the search.
Дополнительные сведения см. в разделе System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Чтобы получить инициализатор класса (статический конструктор) с помощью перегрузки этого метода, необходимо указать BindingFlags.Static | BindingFlags.NonPublic ( BindingFlags.Static Or
BindingFlags.NonPublic в Visual Basic).To get the class initializer (static constructor) using this method overload, you must specify BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOr
BindingFlags.NonPublic in Visual Basic). Можно также получить инициализатор класса с помощью TypeInitializer Свойства.You can also get the class initializer using the TypeInitializer property.
Примечание
Нельзя опустить параметры при поиске конструкторов и методов.You cannot omit parameters when looking up constructors and methods. При вызове можно опустить только параметры.You can only omit parameters when invoking.
Если текущий объект Type представляет сконструированный универсальный тип, этот метод возвращает объект ConstructorInfo с параметрами типа, замененными соответствующими аргументами типа.If the current Type represents a constructed generic type, this method returns the ConstructorInfo with the type parameters replaced by the appropriate type arguments. Если Current Type представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращает значение null
.If the current Type represents a type parameter in the definition of a generic type or generic method, this method always returns null
.
См. также раздел
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Применяется к
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
Выполняет поиск конструктора с параметрами, соответствующими указанным модификаторам и типам аргументов, с учетом заданных ограничений по привязке и соглашений о вызовах.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
public:
System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
virtual System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.ConstructorInfo? GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.ConstructorInfo GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor (System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, binder As Binder, callConvention As CallingConventions, types As Type(), modifiers As ParameterModifier()) As ConstructorInfo
Параметры
- bindingAttr
- BindingFlags
Побитовое сочетание значений перечисления, указывающих способ проведения поиска.A bitwise combination of the enumeration values that specify how the search is conducted.
- или --or-
Default для возврата null
.Default to return null
.
- binder
- Binder
Объект, определяющий набор свойств и разрешающий привязку, что может включать выбор перегруженных методов, приведение типов аргументов и вызов члена с помощью отражения.An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.
- или --or-
Пустая ссылка (Nothing
в Visual Basic) для использования свойства DefaultBinder.A null reference (Nothing
in Visual Basic), to use the DefaultBinder.
- callConvention
- CallingConventions
Объект, определяющий набор применяемых правил, касающихся порядка и расположения аргументов, способа передачи возвращаемого значения, регистров, используемых для аргументов, и очистки стека.The object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and the stack is cleaned up.
- types
- Type[]
Массив объектов Type, предоставляющий число, порядок и тип параметров, извлекаемых конструктором.An array of Type objects representing the number, order, and type of the parameters for the constructor to get.
- или --or- Пустой массив объектов типа Type (то есть Type[] types = new Type[0]), если требуется получить конструктор, который не имеет параметров.An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
- modifiers
- ParameterModifier[]
Массив объектов ParameterModifier, представляющих атрибуты, связанные с соответствующим элементом в массиве types
.An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types
array. Связыватель по умолчанию не обрабатывает этот параметр.The default binder does not process this parameter.
Возвращаемое значение
Если поиск выполнен удачно, возвращается объект, представляющий конструктор, который соответствует указанным требованиям; в противном случае возвращается значение null
.An object representing the constructor that matches the specified requirements, if found; otherwise, null
.
Реализации
- Атрибуты
Исключения
types
имеет значение null
.types
is null
.
- или --or-
Один из элементов в types
имеет значение null
.One of the elements in types
is null
.
Массив types
является многомерным.types
is multidimensional.
- или --or-
Массив modifiers
является многомерным.modifiers
is multidimensional.
- или --or-
types
и modifiers
имеют разную длину.types
and modifiers
do not have the same length.
Примеры
Следующий пример получает тип MyClass
, возвращает ConstructorInfo объект и отображает сигнатуру конструктора.The following example obtains the type of MyClass
, gets the ConstructorInfo object, and displays the constructor signature.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
MyClass1( int i ){}
};
int main()
{
try
{
Type^ myType = MyClass1::typeid;
array<Type^>^types = gcnew array<Type^>(1);
types[ 0 ] = int::typeid;
// Get the public instance constructor that takes an integer parameter.
ConstructorInfo^ constructorInfoObj = myType->GetConstructor( static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public), nullptr, CallingConventions::HasThis, types, nullptr );
if ( constructorInfoObj != nullptr )
{
Console::WriteLine( "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is: " );
Console::WriteLine( constructorInfoObj );
}
else
{
Console::WriteLine( "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is not available." );
}
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "ArgumentNullException: {0}", e->Message );
}
catch ( ArgumentException^ e )
{
Console::WriteLine( "ArgumentException: {0}", e->Message );
}
catch ( SecurityException^ e )
{
Console::WriteLine( "SecurityException: {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
public class MyClass1
{
public MyClass1(int i){}
public static void Main()
{
try
{
Type myType = typeof(MyClass1);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the public instance constructor that takes an integer parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public, null,
CallingConventions.HasThis, types, null);
if(constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass1 that is a public " +
"instance method and takes an integer as a parameter is: ");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of MyClass1 that is a public instance " +
"method and takes an integer as a parameter is not available.");
}
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
catch(ArgumentException e)
{
Console.WriteLine("ArgumentException: " + e.Message);
}
catch(SecurityException e)
{
Console.WriteLine("SecurityException: " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
Public Class MyClass1
Public Sub New(ByVal i As Integer)
End Sub
Public Shared Sub Main()
Try
Dim myType As Type = GetType(MyClass1)
Dim types(0) As Type
types(0) = GetType(Integer)
' Get the public instance constructor that takes an integer parameter.
Dim constructorInfoObj As ConstructorInfo = _
myType.GetConstructor(BindingFlags.Instance Or _
BindingFlags.Public, Nothing, _
CallingConventions.HasThis, types, Nothing)
If Not (constructorInfoObj Is Nothing) Then
Console.WriteLine("The constructor of MyClass1 that " + _
"is a public instance method and takes an " + _
"integer as a parameter is: ")
Console.WriteLine(constructorInfoObj.ToString())
Else
Console.WriteLine("The constructor MyClass1 that " + _
"is a public instance method and takes an " + _
"integer as a parameter is not available.")
End If
Catch e As ArgumentNullException
Console.WriteLine("ArgumentNullException: " + e.Message)
Catch e As ArgumentException
Console.WriteLine("ArgumentException: " + e.Message)
Catch e As SecurityException
Console.WriteLine("SecurityException: " + e.Message)
Catch e As Exception
Console.WriteLine("Exception: " + e.Message)
End Try
End Sub
End Class
Комментарии
Хотя связыватель по умолчанию не обрабатывается ParameterModifier ( modifiers
параметр), можно использовать абстрактный System.Reflection.Binder класс для написания пользовательского связывателя, который обрабатывает modifiers
.Although the default binder does not process ParameterModifier (the modifiers
parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers
. ParameterModifier
используется только при вызове через COM-взаимодействие, и обрабатываются только параметры, передаваемые по ссылке.ParameterModifier
is only used when calling through COM interop, and only parameters that are passed by reference are handled.
Если точное соответствие не существует, binder
будет предпринята попытка привести типы параметров, заданные в types
массиве, для выбора совпадения.If an exact match does not exist, the binder
will attempt to coerce the parameter types specified in the types
array in order to select a match. Если binder
не удается выбрать соответствие, null
возвращается значение.If the binder
is unable to select a match, then null
is returned.
BindingFlagsДля определения конструкторов, включаемых в поиск, можно использовать следующие флаги фильтра:The following BindingFlags filter flags can be used to define which constructors to include in the search:
Необходимо указать или,
BindingFlags.Instance
BindingFlags.Static
чтобы получить возвращаемое значение.You must specify eitherBindingFlags.Instance
orBindingFlags.Static
in order to get a return.Укажите
BindingFlags.Public
, чтобы включить в поиск открытые конструкторы.SpecifyBindingFlags.Public
to include public constructors in the search.Укажите
BindingFlags.NonPublic
для включения в поиск неоткрытых конструкторов (т. е. закрытых, внутренних и защищенных конструкторов).SpecifyBindingFlags.NonPublic
to include non-public constructors (that is, private, internal, and protected constructors) in the search.
Дополнительные сведения см. в разделе System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Чтобы получить инициализатор класса (статический конструктор) с помощью этого метода, необходимо указать BindingFlags.Static | BindingFlags.NonPublic ( BindingFlags.Static Or
BindingFlags.NonPublic в Visual Basic).To get the class initializer (static constructor) using this method, you must specify BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOr
BindingFlags.NonPublic in Visual Basic). Можно также получить инициализатор класса с помощью TypeInitializer Свойства.You can also get the class initializer using the TypeInitializer property.
В следующей таблице показано, какие члены базового класса возвращаются Get
методами при отражении в типе.The following table shows what members of a base class are returned by the Get
methods when reflecting on a type.
Тип членаMember Type | СтатическиеStatic | Не статическийNon-Static |
---|---|---|
КонструкторConstructor | НетNo | НетNo |
ПолеField | НетNo | Да.Yes. Поле всегда скрывается по имени и сигнатуре.A field is always hide-by-name-and-signature. |
СобытиеEvent | НеприменимоNot applicable | Правило системы общих типов — это то же наследование, что и методы, реализующие свойство.The common type system rule is that the inheritance is the same as that of the methods that implement the property. Отражение рассматривает свойства как скрытые по имени и сигнатуре.Reflection treats properties as hide-by-name-and-signature. См. Примечание 2 ниже.See note 2 below. |
МетодMethod | НетNo | Да.Yes. Метод (как виртуальный, так и невиртуальный) может быть скрыт по имени или скрытию по имени и сигнатуре.A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Вложенный типNested Type | НетNo | НетNo |
Свойство.Property | НеприменимоNot applicable | Правило системы общих типов — это то же наследование, что и методы, реализующие свойство.The common type system rule is that the inheritance is the same as that of the methods that implement the property. Отражение рассматривает свойства как скрытые по имени и сигнатуре.Reflection treats properties as hide-by-name-and-signature. См. Примечание 2 ниже.See note 2 below. |
При скрытии по имени и сигнатуре учитываются все части сигнатуры, включая пользовательские модификаторы, возвращаемые типы, типы параметров, Sentinel и неуправляемые соглашения о вызовах.Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. Это двоичное сравнение.This is a binary comparison.
Для отражения свойства и события скрываются по имени и сигнатуре.For reflection, properties and events are hide-by-name-and-signature. Если у вас есть свойство с методом доступа get и Set в базовом классе, но производный класс имеет только метод доступа get, свойство производного класса скрывает свойство базового класса, и вы не сможете получить доступ к методу задания в базовом классе.If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
Настраиваемые атрибуты не являются частью системы общих типов.Custom attributes are not part of the common type system.
Примечание
Нельзя опустить параметры при поиске конструкторов и методов.You cannot omit parameters when looking up constructors and methods. При вызове можно опустить только параметры.You can only omit parameters when invoking.
Если текущий объект Type представляет сконструированный универсальный тип, этот метод возвращает объект ConstructorInfo с параметрами типа, замененными соответствующими аргументами типа.If the current Type represents a constructed generic type, this method returns the ConstructorInfo with the type parameters replaced by the appropriate type arguments. Если Current Type представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращает значение null
.If the current Type represents a type parameter in the definition of a generic type or generic method, this method always returns null
.
См. также раздел
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- CallingConventions
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()