Type.GetMembers Метод
Определение
Перегрузки
GetMembers() |
Возвращает все открытые члены текущего объекта Type.Returns all the public members of the current Type. |
GetMembers(BindingFlags) |
При переопределении в производном классе ищет члены, определенные для текущего объекта Type, используя указанные ограничения привязки.When overridden in a derived class, searches for the members defined for the current Type, using the specified binding constraints. |
GetMembers()
Возвращает все открытые члены текущего объекта Type.Returns all the public members of the current Type.
public:
virtual cli::array <System::Reflection::MemberInfo ^> ^ GetMembers();
public System.Reflection.MemberInfo[] GetMembers ();
abstract member GetMembers : unit -> System.Reflection.MemberInfo[]
override this.GetMembers : unit -> System.Reflection.MemberInfo[]
Public Function GetMembers () As MemberInfo()
Возвраты
Массив объектов MemberInfo, представляющий все открытые члены текущего типа Type.An array of MemberInfo objects representing all the public members of the current Type.
- или --or- Пустой массив типа MemberInfo, если у текущего типа Type нет открытых членов.An empty array of type MemberInfo, if the current Type does not have public members.
Реализации
Примеры
В следующем примере кода показано, как использовать перегрузку метода GetMembers() для получения сведений обо всех открытых членах указанного класса.The following code example demonstrates how to use the GetMembers() method overload to collect information about all public members of a specified class.
ref class MyClass
{
public:
int myInt;
String^ myString;
MyClass(){}
void Myfunction(){}
};
int main()
{
try
{
MyClass^ myObject = gcnew MyClass;
array<MemberInfo^>^myMemberInfo;
// Get the type of 'MyClass'.
Type^ myType = myObject->GetType();
// Get the information related to all public members of 'MyClass'.
myMemberInfo = myType->GetMembers();
Console::WriteLine( "\nThe members of class '{0}' are :\n", myType );
for ( int i = 0; i < myMemberInfo->Length; i++ )
{
// Display name and type of the concerned member.
Console::WriteLine( "'{0}' is a {1}", myMemberInfo[ i ]->Name, myMemberInfo[ i ]->MemberType );
}
}
catch ( SecurityException^ e )
{
Console::WriteLine( "Exception : {0}", e->Message );
}
}
class MyClass
{
public int myInt = 0;
public string myString = null;
public MyClass()
{
}
public void Myfunction()
{
}
}
class Type_GetMembers
{
public static void Main()
{
try
{
MyClass myObject = new MyClass();
MemberInfo[] myMemberInfo;
// Get the type of 'MyClass'.
Type myType = myObject.GetType();
// Get the information related to all public member's of 'MyClass'.
myMemberInfo = myType.GetMembers();
Console.WriteLine( "\nThe members of class '{0}' are :\n", myType);
for (int i =0 ; i < myMemberInfo.Length ; i++)
{
// Display name and type of the concerned member.
Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType);
}
}
catch(SecurityException e)
{
Console.WriteLine("Exception : " + e.Message );
}
}
}
Class [MyClass]
Public myInt As Integer = 0
Public myString As String = Nothing
Public Sub New()
End Sub
Public Sub Myfunction()
End Sub
End Class
Class Type_GetMembers
Public Shared Sub Main()
Try
Dim myObject As New [MyClass]()
Dim myMemberInfo() As MemberInfo
' Get the type of 'MyClass'.
Dim myType As Type = myObject.GetType()
' Get the information related to all public member's of 'MyClass'.
myMemberInfo = myType.GetMembers()
Console.WriteLine(ControlChars.Cr + "The members of class '{0}' are :" + ControlChars.Cr, myType)
Dim i As Integer
For i = 0 To myMemberInfo.Length - 1
' Display name and type of the concerned member.
Console.WriteLine("'{0}' is a {1}", myMemberInfo(i).Name, myMemberInfo(i).MemberType)
Next i
Catch e As SecurityException
Console.WriteLine(("Exception : " + e.Message.ToString()))
End Try
End Sub
End Class
Комментарии
К элементам относятся свойства, методы, конструкторы, поля, события и вложенные типы.Members include properties, methods, constructors, fields, events, and nested types.
Метод GetMembers не возвращает элементы в определенном порядке, например алфавит или порядок объявления.The GetMembers method does not return members in a particular order, such as alphabetical or declaration order. Код не должен зависеть от порядка, в котором возвращаются элементы, так как этот порядок меняется.Your code must not depend on the order in which members are returned, because that order varies.
Эта перегрузка метода вызывает перегрузку метода GetMembers(BindingFlags) с BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static (BindingFlags.PublicOr
BindingFlags.InstanceOr
BindingFlags.Static).This method overload calls the GetMembers(BindingFlags) method overload, with BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static (BindingFlags.PublicOr
BindingFlags.InstanceOr
BindingFlags.Static in Visual Basic). Инициализаторы классов не будут найдены (статические конструкторы).It will not find class initializers (static constructors). Чтобы найти инициализаторы классов, вызовите перегрузку GetMembers(BindingFlags) и укажите | BindingFlags.Static BindingFlags.NonPublic (BindingFlags.StaticOr
BindingFlags.NonPublic в Visual Basic).To find class initializers, call the GetMembers(BindingFlags) overload, 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.
В следующей таблице показаны элементы базового класса, возвращаемые методами 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.
Если текущий Type представляет сконструированный универсальный тип, этот метод возвращает объекты MemberInfo с параметрами типа, замененными соответствующими аргументами типа.If the current Type represents a constructed generic type, this method returns the MemberInfo objects with the type parameters replaced by the appropriate type arguments.
Если текущий Type представляет параметр типа в определении универсального типа или универсального метода, этот метод ищет члены ограничения класса или члены Object, если ограничение класса отсутствует.If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the members of the class constraint, or the members of Object if there is no class constraint.
Дополнительно
GetMembers(BindingFlags)
При переопределении в производном классе ищет члены, определенные для текущего объекта Type, используя указанные ограничения привязки.When overridden in a derived class, searches for the members defined for the current Type, using the specified binding constraints.
public:
abstract cli::array <System::Reflection::MemberInfo ^> ^ GetMembers(System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.MemberInfo[] GetMembers (System.Reflection.BindingFlags bindingAttr);
abstract member GetMembers : System.Reflection.BindingFlags -> System.Reflection.MemberInfo[]
Public MustOverride Function GetMembers (bindingAttr As BindingFlags) As MemberInfo()
Параметры
- bindingAttr
- BindingFlags
Побитовое сочетание значений перечисления, указывающих способ проведения поиска.A bitwise combination of the enumeration values that specify how the search is conducted.
- или --or- Default для возврата пустого массива.Default to return an empty array.
Возвраты
Массив объектов MemberInfo, представляющий все члены, определенные для текущего типа Type и удовлетворяющие указанным ограничениям привязки.An array of MemberInfo objects representing all members defined for the current Type that match the specified binding constraints.
- или --or- Пустой массив, если для текущего объекта Type не определены члены или ни один из определенных членов не удовлетворяет ограничениям привязки.An empty array if no members are defined for the current Type, or if none of the defined members match the binding constraints.
Реализации
Примеры
В следующем примере кода показано, как использовать перегрузку метода GetMembers(BindingFlags) для получения сведений обо всех открытых членах экземпляра указанного класса.The following code example demonstrates how to use the GetMembers(BindingFlags) method overload to collect information about all public instance members of a specified class.
ref class MyClass
{
public:
int * myInt;
String^ myString;
MyClass(){}
void Myfunction(){}
};
int main()
{
try
{
MyClass^ MyObject = gcnew MyClass;
array<MemberInfo^>^myMemberInfo;
// Get the type of the class 'MyClass'.
Type^ myType = MyObject->GetType();
// Get the public instance members of the class 'MyClass'.
myMemberInfo = myType->GetMembers( static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
Console::WriteLine( "\nThe public instance members of class '{0}' are : \n", myType );
for ( int i = 0; i < myMemberInfo->Length; i++ )
{
// Display name and type of the member of 'MyClass'.
Console::WriteLine( "'{0}' is a {1}", myMemberInfo[ i ]->Name, myMemberInfo[ i ]->MemberType );
}
}
catch ( SecurityException^ e )
{
Console::WriteLine( "SecurityException : {0}", e->Message );
}
//Output:
//The public instance members of class 'MyClass' are :
//'Myfunction' is a Method
//'ToString' is a Method
//'Equals' is a Method
//'GetHashCode' is a Method
//'GetType' is a Method
//'.ctor' is a Constructor
//'myInt' is a Field
//'myString' is a Field
}
class MyClass
{
public int myInt = 0;
public string myString = null;
public MyClass()
{
}
public void Myfunction()
{
}
}
class Type_GetMembers_BindingFlags
{
public static void Main()
{
try
{
MyClass MyObject = new MyClass();
MemberInfo [] myMemberInfo;
// Get the type of the class 'MyClass'.
Type myType = MyObject.GetType();
// Get the public instance members of the class 'MyClass'.
myMemberInfo = myType.GetMembers(BindingFlags.Public|BindingFlags.Instance);
Console.WriteLine( "\nThe public instance members of class '{0}' are : \n", myType);
for (int i =0 ; i < myMemberInfo.Length ; i++)
{
// Display name and type of the member of 'MyClass'.
Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType);
}
}
catch (SecurityException e)
{
Console.WriteLine("SecurityException : " + e.Message );
}
//Output:
//The public instance members of class 'MyClass' are :
//'Myfunction' is a Method
//'ToString' is a Method
//'Equals' is a Method
//'GetHashCode' is a Method
//'GetType' is a Method
//'.ctor' is a Constructor
//'myInt' is a Field
//'myString' is a Field
}
}
Class [MyClass]
Public myInt As Integer = 0
Public myString As String = Nothing
Public Sub New()
End Sub
Public Sub Myfunction()
End Sub
End Class
Class Type_GetMembers_BindingFlags
Public Shared Sub Main()
Try
Dim MyObject As New [MyClass]()
Dim myMemberInfo() As MemberInfo
' Get the type of the class 'MyClass'.
Dim myType As Type = MyObject.GetType()
' Get the public instance members of the class 'MyClass'.
myMemberInfo = myType.GetMembers((BindingFlags.Public Or BindingFlags.Instance))
Console.WriteLine(ControlChars.Cr + "The public instance members of class '{0}' are : " + ControlChars.Cr, myType)
Dim i As Integer
For i = 0 To myMemberInfo.Length - 1
' Display name and type of the member of 'MyClass'.
Console.WriteLine("'{0}' is a {1}", myMemberInfo(i).Name, myMemberInfo(i).MemberType)
Next i
Catch e As SecurityException
Console.WriteLine(("SecurityException : " + e.Message.ToString()))
End Try
'Output:
'The public instance members of class 'MyClass' are :
''Myfunction' is a Method
''ToString' is a Method
''Equals' is a Method
''GetHashCode' is a Method
''GetType' is a Method
''.ctor' is a Constructor
''myInt' is a Field
''myString' is a Field
End Sub
End Class
Комментарии
К элементам относятся свойства, методы, конструкторы, поля, события и вложенные типы.Members include properties, methods, constructors, fields, events, and nested types.
Чтобы перегрузить GetMethods(BindingFlags)
для успешного получения сведений о методе, аргумент bindingAttr
должен включать по крайней мере один из BindingFlags.Instance и BindingFlags.Static, а также хотя бы один из BindingFlags.NonPublic и BindingFlags.Public.For the GetMethods(BindingFlags)
overload to successfully retrieve method information, the bindingAttr
argument must include at least one of BindingFlags.Instance and BindingFlags.Static, along with at least one of BindingFlags.NonPublic and BindingFlags.Public. Единственное исключение — вызов метода с BindingFlags.NonPublic, который возвращает сведения об элементе о вложенных типах.The sole exception is a method call with BindingFlags.NonPublic, which returns member information about nested types.
Для определения элементов, включаемых в поиск, можно использовать следующие флаги фильтра BindingFlags.The following BindingFlags filter flags can be used to define which members to include in the search:
Укажите
BindingFlags.Instance
, чтобы включить методы экземпляра.SpecifyBindingFlags.Instance
to include instance methods.Укажите
BindingFlags.Static
, чтобы включить статические методы.SpecifyBindingFlags.Static
to include static methods.Укажите
BindingFlags.Public
, чтобы включить в поиск открытые методы.SpecifyBindingFlags.Public
to include public methods in the search.Укажите
BindingFlags.NonPublic
, чтобы включить в поиск неоткрытые методы (т. е. частные, внутренние и защищенные методы).SpecifyBindingFlags.NonPublic
to include non-public methods (that is, private, internal, and protected methods) in the search. Возвращаются только защищенные и внутренние методы базовых классов. закрытые методы в базовых классах не возвращаются.Only protected and internal methods on base classes are returned; private methods on base classes are not returned.Укажите
BindingFlags.FlattenHierarchy
, чтобы включитьpublic
иprotected
статические элементы в иерархии.private
статические члены в унаследованных классах не включены.SpecifyBindingFlags.FlattenHierarchy
to includepublic
andprotected
static members up the hierarchy;private
static members in inherited classes are not included.Укажите только
BindingFlags.Default
, чтобы вернуть пустой массив MethodInfo.SpecifyBindingFlags.Default
alone to return an empty MethodInfo array.
Для изменения работы поиска можно использовать следующие флаги модификатора BindingFlags.The following BindingFlags modifier flags can be used to change how the search works:
BindingFlags.DeclaredOnly
искать только члены, объявленные в Type, а не члены, которые были просто унаследованы.BindingFlags.DeclaredOnly
to search only the members declared on the Type, not members that were simply inherited.
Дополнительные сведения см. в разделе System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Метод GetMembers не возвращает элементы в определенном порядке, например алфавит или порядок объявления.The GetMembers method does not return members in a particular order, such as alphabetical or declaration order. Код не должен зависеть от порядка, в котором возвращаются элементы, так как этот порядок меняется.Your code must not depend on the order in which members are returned, because that order varies.
Чтобы получить инициализатор класса (статический конструктор) с помощью этой перегрузки метода, необходимо указать | BindingFlags.Static BindingFlags.NonPublic (BindingFlags.StaticOr
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.
Если текущий Type представляет сконструированный универсальный тип, этот метод возвращает объекты MemberInfo с параметрами типа, замененными соответствующими аргументами типа.If the current Type represents a constructed generic type, this method returns the MemberInfo objects with the type parameters replaced by the appropriate type arguments.
Если текущий Type представляет параметр типа в определении универсального типа или универсального метода, этот метод ищет члены ограничения класса или члены Object, если ограничение класса отсутствует.If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the members of the class constraint, or the members of Object if there is no class constraint.