Type.GetField Método
Definición
Sobrecargas
GetField(String) |
Busca el campo público con el nombre especificado.Searches for the public field with the specified name. |
GetField(String, BindingFlags) |
Busca el campo especificado mediante las restricciones de enlace especificadas.Searches for the specified field, using the specified binding constraints. |
GetField(String)
Busca el campo público con el nombre especificado.Searches for the public field with the specified name.
public:
System::Reflection::FieldInfo ^ GetField(System::String ^ name);
public:
virtual System::Reflection::FieldInfo ^ GetField(System::String ^ name);
public System.Reflection.FieldInfo? GetField (string name);
public System.Reflection.FieldInfo GetField (string name);
member this.GetField : string -> System.Reflection.FieldInfo
abstract member GetField : string -> System.Reflection.FieldInfo
override this.GetField : string -> System.Reflection.FieldInfo
Public Function GetField (name As String) As FieldInfo
Parámetros
- name
- String
Cadena que contiene el nombre del campo de datos que se va a obtener.The string containing the name of the data field to get.
Devoluciones
Objeto que representa el campo público con el nombre especificado, si se encuentra; en caso contrario, null
.An object representing the public field with the specified name, if found; otherwise, null
.
Implementaciones
Excepciones
name
es null
.name
is null
.
Este objeto Type es un TypeBuilder a cuyo método CreateType() aún no se ha llamado.This Type object is a TypeBuilder whose CreateType() method has not yet been called.
Ejemplos
En el ejemplo siguiente se obtiene el Type
objeto de la clase especificada, se obtiene el FieldInfo objeto para el campo y se muestra el valor del campo.The following example gets the Type
object for the specified class, obtains the FieldInfo object for the field, and displays the value of the field.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyFieldClassA
{
public:
String^ field;
MyFieldClassA()
{
field = "A Field";
}
property String^ Field
{
String^ get()
{
return field;
}
void set( String^ value )
{
if ( field != value )
{
field = value;
}
}
}
};
public ref class MyFieldClassB
{
public:
String^ field;
MyFieldClassB()
{
field = "B Field";
}
property String^ Field
{
String^ get()
{
return field;
}
void set( String^ value )
{
if ( field != value )
{
field = value;
}
}
}
};
int main()
{
try
{
MyFieldClassB^ myFieldObjectB = gcnew MyFieldClassB;
MyFieldClassA^ myFieldObjectA = gcnew MyFieldClassA;
Type^ myTypeA = Type::GetType( "MyFieldClassA" );
FieldInfo^ myFieldInfo = myTypeA->GetField( "field" );
Type^ myTypeB = Type::GetType( "MyFieldClassB" );
FieldInfo^ myFieldInfo1 = myTypeB->GetField( "field", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
Console::WriteLine( "The value of the field is : {0} ", myFieldInfo->GetValue( myFieldObjectA ) );
Console::WriteLine( "The value of the field is : {0} ", myFieldInfo1->GetValue( myFieldObjectB ) );
}
catch ( SecurityException^ e )
{
Console::WriteLine( "Exception Raised!" );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "Exception Raised!" );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception Raised!" );
Console::WriteLine( "Message : {0}", e->Message );
}
}
using System;
using System.Reflection;
public class MyFieldClassA
{
public string Field = "A Field";
}
public class MyFieldClassB
{
private string field = "B Field";
public string Field
{
get
{
return field;
}
set
{
if (field!=value)
{
field=value;
}
}
}
}
public class MyFieldInfoClass
{
public static void Main()
{
MyFieldClassB myFieldObjectB = new MyFieldClassB();
MyFieldClassA myFieldObjectA = new MyFieldClassA();
Type myTypeA = typeof(MyFieldClassA);
FieldInfo myFieldInfo = myTypeA.GetField("Field");
Type myTypeB = typeof(MyFieldClassB);
FieldInfo myFieldInfo1 = myTypeB.GetField("field",
BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("The value of the public field is: '{0}'",
myFieldInfo.GetValue(myFieldObjectA));
Console.WriteLine("The value of the private field is: '{0}'",
myFieldInfo1.GetValue(myFieldObjectB));
}
}
Imports System.Reflection
Public Class MyFieldClassA
Public Field As String = "A Field"
End Class
Public Class MyFieldClassB
Private myField As String = "B Field"
Public Property Field() As String
Get
Return myField
End Get
Set(ByVal Value As String)
If myField <> value Then
myField = value
End If
End Set
End Property
End Class
Public Class MyFieldInfoClass
Public Shared Sub Main()
Dim myFieldObjectB As New MyFieldClassB()
Dim myFieldObjectA As New MyFieldClassA()
Dim myTypeA As Type = GetType(MyFieldClassA)
Dim myFieldInfo As FieldInfo = myTypeA.GetField("Field")
Dim myTypeB As Type = GetType(MyFieldClassB)
Dim myFieldInfo1 As FieldInfo = myTypeB.GetField("myField", _
BindingFlags.NonPublic Or BindingFlags.Instance)
Console.WriteLine("The value of the public field is: '{0}'", _
myFieldInfo.GetValue(myFieldObjectA))
Console.WriteLine("The value of the private field is: '{0}'", _
myFieldInfo1.GetValue(myFieldObjectB))
End Sub
End Class
Comentarios
La búsqueda de distingue name
entre mayúsculas y minúsculas.The search for name
is case-sensitive. La búsqueda incluye campos públicos estáticos y de instancia pública.The search includes public static and public instance fields.
Si el actual Type representa un tipo genérico construido, este método devuelve FieldInfo con los parámetros de tipo reemplazados por los argumentos de tipo adecuados.If the current Type represents a constructed generic type, this method returns the FieldInfo with the type parameters replaced by the appropriate type arguments.
Si el actual Type representa un parámetro de tipo en la definición de un tipo genérico o de un método genérico, este método busca en los campos de la restricción de clase.If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the fields of the class constraint.
Consulte también
Se aplica a
GetField(String, BindingFlags)
Busca el campo especificado mediante las restricciones de enlace especificadas.Searches for the specified field, using the specified binding constraints.
public:
abstract System::Reflection::FieldInfo ^ GetField(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo? GetField (string name, System.Reflection.BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo GetField (string name, System.Reflection.BindingFlags bindingAttr);
abstract member GetField : string * System.Reflection.BindingFlags -> System.Reflection.FieldInfo
Public MustOverride Function GetField (name As String, bindingAttr As BindingFlags) As FieldInfo
Parámetros
- name
- String
Cadena que contiene el nombre del campo de datos que se va a obtener.The string containing the name of the data field to get.
- bindingAttr
- BindingFlags
Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.A bitwise combination of the enumeration values that specify how the search is conducted.
o bien-or-
Default para devolver null
.Default to return null
.
Devoluciones
Objeto que representa el campo que cumple los requisitos especificados, si se encuentra; en caso contrario, es null
.An object representing the field that matches the specified requirements, if found; otherwise, null
.
Implementaciones
Excepciones
name
es null
.name
is null
.
Ejemplos
En el ejemplo siguiente se obtiene el Type
objeto de la clase especificada, se obtiene el FieldInfo objeto para el campo que coincide con las marcas de enlace especificadas y se muestra el valor del campo.The following example gets the Type
object for the specified class, obtains the FieldInfo object for the field that matches the specified binding flags, and displays the value of the field.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyFieldClassA
{
public:
String^ field;
MyFieldClassA()
{
field = "A Field";
}
property String^ Field
{
String^ get()
{
return field;
}
void set( String^ value )
{
if ( field != value )
{
field = value;
}
}
}
};
public ref class MyFieldClassB
{
public:
String^ field;
MyFieldClassB()
{
field = "B Field";
}
property String^ Field
{
String^ get()
{
return field;
}
void set( String^ value )
{
if ( field != value )
{
field = value;
}
}
}
};
int main()
{
try
{
MyFieldClassB^ myFieldObjectB = gcnew MyFieldClassB;
MyFieldClassA^ myFieldObjectA = gcnew MyFieldClassA;
Type^ myTypeA = Type::GetType( "MyFieldClassA" );
FieldInfo^ myFieldInfo = myTypeA->GetField( "field" );
Type^ myTypeB = Type::GetType( "MyFieldClassB" );
FieldInfo^ myFieldInfo1 = myTypeB->GetField( "field", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
Console::WriteLine( "The value of the field is : {0} ", myFieldInfo->GetValue( myFieldObjectA ) );
Console::WriteLine( "The value of the field is : {0} ", myFieldInfo1->GetValue( myFieldObjectB ) );
}
catch ( SecurityException^ e )
{
Console::WriteLine( "Exception Raised!" );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "Exception Raised!" );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception Raised!" );
Console::WriteLine( "Message : {0}", e->Message );
}
}
using System;
using System.Reflection;
public class MyFieldClassA
{
public string Field = "A Field";
}
public class MyFieldClassB
{
private string field = "B Field";
public string Field
{
get
{
return field;
}
set
{
if (field!=value)
{
field=value;
}
}
}
}
public class MyFieldInfoClass
{
public static void Main()
{
MyFieldClassB myFieldObjectB = new MyFieldClassB();
MyFieldClassA myFieldObjectA = new MyFieldClassA();
Type myTypeA = typeof(MyFieldClassA);
FieldInfo myFieldInfo = myTypeA.GetField("Field");
Type myTypeB = typeof(MyFieldClassB);
FieldInfo myFieldInfo1 = myTypeB.GetField("field",
BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("The value of the public field is: '{0}'",
myFieldInfo.GetValue(myFieldObjectA));
Console.WriteLine("The value of the private field is: '{0}'",
myFieldInfo1.GetValue(myFieldObjectB));
}
}
Imports System.Reflection
Public Class MyFieldClassA
Public Field As String = "A Field"
End Class
Public Class MyFieldClassB
Private myField As String = "B Field"
Public Property Field() As String
Get
Return myField
End Get
Set(ByVal Value As String)
If myField <> value Then
myField = value
End If
End Set
End Property
End Class
Public Class MyFieldInfoClass
Public Shared Sub Main()
Dim myFieldObjectB As New MyFieldClassB()
Dim myFieldObjectA As New MyFieldClassA()
Dim myTypeA As Type = GetType(MyFieldClassA)
Dim myFieldInfo As FieldInfo = myTypeA.GetField("Field")
Dim myTypeB As Type = GetType(MyFieldClassB)
Dim myFieldInfo1 As FieldInfo = myTypeB.GetField("myField", _
BindingFlags.NonPublic Or BindingFlags.Instance)
Console.WriteLine("The value of the public field is: '{0}'", _
myFieldInfo.GetValue(myFieldObjectA))
Console.WriteLine("The value of the private field is: '{0}'", _
myFieldInfo1.GetValue(myFieldObjectB))
End Sub
End Class
Comentarios
En la tabla siguiente se muestra qué miembros de una clase base son devueltos por los Get
métodos cuando se reflejan en un tipo.The following table shows what members of a base class are returned by the Get
methods when reflecting on a type.
Tipo de miembroMember Type | EstáticoStatic | No estáticaNon-Static |
---|---|---|
ConstructorConstructor | NoNo | NoNo |
CampoField | NoNo | Sí.Yes. Un campo siempre se oculta por nombre y firma.A field is always hide-by-name-and-signature. |
eventoEvent | No es aplicableNot applicable | La regla del sistema de tipos comunes es que la herencia es la misma que la de los métodos que implementan la propiedad.The common type system rule is that the inheritance is the same as that of the methods that implement the property. La reflexión trata las propiedades como ocultas por nombre y firma.Reflection treats properties as hide-by-name-and-signature. Vea la nota 2 a continuación.See note 2 below. |
MétodoMethod | NoNo | Sí.Yes. Un método (tanto virtual como no virtual) se puede ocultar por nombre u ocultar por nombre y por firma.A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Tipo anidadoNested Type | NoNo | NoNo |
Propiedad.Property | No es aplicableNot applicable | La regla del sistema de tipos comunes es que la herencia es la misma que la de los métodos que implementan la propiedad.The common type system rule is that the inheritance is the same as that of the methods that implement the property. La reflexión trata las propiedades como ocultas por nombre y firma.Reflection treats properties as hide-by-name-and-signature. Vea la nota 2 a continuación.See note 2 below. |
Ocultar por nombre y firma tiene en cuenta todas las partes de la firma, incluidos los modificadores personalizados, los tipos de valor devuelto, los tipos de parámetros, los Sentinel y las convenciones de llamada no administradas.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. Esta es una comparación binaria.This is a binary comparison.
En la reflexión, las propiedades y los eventos son Hide-by-Name y Signature.For reflection, properties and events are hide-by-name-and-signature. Si tiene una propiedad con un descriptor de acceso get y set en la clase base, pero la clase derivada solo tiene un descriptor de acceso get, la propiedad de la clase derivada oculta la propiedad de clase base y no podrá tener acceso al establecedor en la clase base.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.
Los atributos personalizados no forman parte del sistema de tipos comunes.Custom attributes are not part of the common type system.
BindingFlagsSe pueden usar las siguientes marcas de filtro para definir los campos que se van a incluir en la búsqueda:The following BindingFlags filter flags can be used to define which fields to include in the search:
Debe especificar
BindingFlags.Instance
oBindingFlags.Static
para obtener un valor devuelto.You must specify eitherBindingFlags.Instance
orBindingFlags.Static
in order to get a return.Especifique
BindingFlags.Public
que se incluyan los campos públicos en la búsqueda.SpecifyBindingFlags.Public
to include public fields in the search.Especifique
BindingFlags.NonPublic
que se incluyan campos no públicos (es decir, campos privados, internos y protegidos) en la búsqueda.SpecifyBindingFlags.NonPublic
to include non-public fields (that is, private, internal, and protected fields) in the search.Especifique
BindingFlags.FlattenHierarchy
para incluirpublic
yprotected
miembros estáticos en la jerarquía;private
los miembros estáticos de las clases heredadas no se incluyen.SpecifyBindingFlags.FlattenHierarchy
to includepublic
andprotected
static members up the hierarchy;private
static members in inherited classes are not included.
BindingFlagsSe pueden usar las siguientes marcas de modificador para cambiar el funcionamiento de la búsqueda:The following BindingFlags modifier flags can be used to change how the search works:
BindingFlags.IgnoreCase
para omitir el caso dename
.BindingFlags.IgnoreCase
to ignore the case ofname
.BindingFlags.DeclaredOnly
para buscar solo los campos declarados en Type , no los campos que se han heredado simplemente.BindingFlags.DeclaredOnly
to search only the fields declared on the Type, not fields that were simply inherited.
Vea System.Reflection.BindingFlags para obtener más información.See System.Reflection.BindingFlags for more information.
Si el actual Type representa un tipo genérico construido, este método devuelve FieldInfo con los parámetros de tipo reemplazados por los argumentos de tipo adecuados.If the current Type represents a constructed generic type, this method returns the FieldInfo with the type parameters replaced by the appropriate type arguments.
Si el actual Type representa un parámetro de tipo en la definición de un tipo genérico o de un método genérico, este método busca en los campos de la restricción de clase.If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the fields of the class constraint.