Type.GetProperty Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Obtém uma propriedade específica da corrente Type.
Sobrecargas
| Name | Description |
|---|---|
| GetProperty(String) |
Procura a propriedade pública com o nome especificado. |
| GetProperty(String, BindingFlags) |
Procura a propriedade especificada, usando as restrições de ligação especificadas. |
| GetProperty(String, Type) |
Pesquisa pelo bem público com o nome e tipo de devolução especificados. |
| GetProperty(String, Type[]) |
Pesquisa pela propriedade pública especificada cujos parâmetros correspondem aos tipos de argumentos especificados. |
| GetProperty(String, Type, Type[]) |
Pesquisa pela propriedade pública especificada cujos parâmetros correspondem aos tipos de argumentos especificados. |
| GetProperty(String, Type, Type[], ParameterModifier[]) |
Pesquisa pela propriedade pública especificada cujos parâmetros correspondem aos tipos de argumentos e modificadores especificados. |
| GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) |
Procura a propriedade especificada cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de ligação especificadas. |
GetProperty(String)
Procura a propriedade pública com o nome especificado.
public:
virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name);
public:
System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name);
public System.Reflection.PropertyInfo GetProperty(string name);
abstract member GetProperty : string -> System.Reflection.PropertyInfo
override this.GetProperty : string -> System.Reflection.PropertyInfo
member this.GetProperty : string -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String) As PropertyInfo
Parâmetros
- name
- String
A corda que contém o nome da propriedade pública a obter.
Devoluções
Um objeto que representa a propriedade pública com o nome especificado, se encontrado; caso contrário, null.
Implementações
Exceções
Encontram-se mais do que uma propriedade com o nome especificado.
name é null.
Exemplos
O exemplo seguinte recupera o Type objeto de uma classe definida pelo utilizador, recupera uma propriedade dessa classe e apresenta o nome da propriedade.
using System;
using System.Reflection;
class MyClass1
{
// Declare MyProperty.
public int MyProperty { get; set; }
}
public class MyTypeClass1
{
public static void Main(string[] args)
{
try
{
// Get the Type object corresponding to MyClass1.
Type myType = typeof(MyClass1);
// Get the PropertyInfo object by passing the property name.
PropertyInfo myPropInfo = myType.GetProperty("MyProperty");
// Display the property name.
Console.WriteLine("The {0} property exists in MyClass1.", myPropInfo.Name);
}
catch (NullReferenceException e)
{
Console.WriteLine("The property does not exist in MyClass1." + e.Message);
}
}
}
open System
type MyClass() =
let mutable myProperty = 0
// Declare MyProperty.
member _.MyProperty
with get () =
myProperty
and set (value) =
myProperty <- value
try
// Get the Type object corresponding to MyClass.
let myType = typeof<MyClass>
// Get the PropertyInfo object by passing the property name.
let myPropInfo = myType.GetProperty "MyProperty"
// Display the property name.
printfn $"The {myPropInfo.Name} property exists in MyClass."
with :? NullReferenceException as e ->
printfn $"The property does not exist in MyClass.{e.Message}"
Imports System.Reflection
Class MyClass1
Private myProperty1 As Integer
' Declare MyProperty.
Public Property MyProperty() As Integer
Get
Return MyProperty1
End Get
Set(ByVal Value As Integer)
MyProperty1 = Value
End Set
End Property
End Class
Public Class MyTypeClass
Public Shared Sub Run(ByVal args() As String)
Try
' Get Type Object corresponding to MyClass.
Dim myType As Type = GetType(MyClass1)
' Get PropertyInfo object by passing property name.
Dim myPropInfo As PropertyInfo = myType.GetProperty("MyProperty")
' Display Name property to console.
Console.WriteLine("The {0} property exists in MyClass.", myPropInfo.Name)
Catch e As NullReferenceException
Console.WriteLine("The property does not exist in MyClass.", e.Message.ToString())
End Try
End Sub
End Class
Observações
Para mais informações sobre esta API, consulte Observações suplementares da API para Type.GetProperty.
Ver também
- PropertyInfo
- String
- DefaultBinder
- GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
- GetProperties(BindingFlags)
Aplica-se a
GetProperty(String, BindingFlags)
Procura a propriedade especificada, usando as restrições de ligação especificadas.
public:
virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
public System.Reflection.PropertyInfo GetProperty(string name, System.Reflection.BindingFlags bindingAttr);
abstract member GetProperty : string * System.Reflection.BindingFlags -> System.Reflection.PropertyInfo
override this.GetProperty : string * System.Reflection.BindingFlags -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, bindingAttr As BindingFlags) As PropertyInfo
Parâmetros
- name
- String
A cadeia que contém o nome da propriedade a obter.
- bindingAttr
- BindingFlags
Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.
-ou-
Default para regressar null.
Devoluções
Um objeto que representa a propriedade que corresponde aos requisitos especificados, se for encontrado; caso contrário, null.
Implementações
Exceções
Mais do que uma propriedade é encontrada com o nome especificado e correspondendo às restrições de ligação especificadas.
name é null.
Exemplos
O exemplo seguinte recupera o tipo de uma classe definida pelo utilizador, recupera uma propriedade dessa classe e apresenta o nome da propriedade de acordo com as restrições de ligação especificadas.
using System;
using System.Reflection;
class MyClass2
{
// Declare MyProperty.
public int MyProperty { get; set; }
}
public class MyTypeClass2
{
public static void Main(string[] args)
{
try
{
// Get Type object of MyClass2.
Type myType = typeof(MyClass2);
// Get the PropertyInfo by passing the property name and specifying the BindingFlags.
PropertyInfo myPropInfo = myType.GetProperty(
"MyProperty",
BindingFlags.Public | BindingFlags.Instance
);
// Display Name property to console.
Console.WriteLine("{0} is a property of MyClass2.", myPropInfo.Name);
}
catch (NullReferenceException e)
{
Console.WriteLine("MyProperty does not exist in MyClass2." + e.Message);
}
}
}
open System
open System.Reflection
type MyClass() =
let mutable myProperty = 0
// Declare MyProperty.
member _.MyProperty
with get () =
myProperty
and set (value) =
myProperty <- value
try
// Get Type object of MyClass.
let myType = typeof<MyClass>
// Get the PropertyInfo by passing the property name and specifying the BindingFlags.
let myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public ||| BindingFlags.Instance)
// Display Name property to console.
printfn $"{myPropInfo.Name} is a property of MyClass."
with :? NullReferenceException as e ->
printfn $"MyProperty does not exist in MyClass.{e.Message}"
Imports System.Reflection
Module Module1
Public Class MyClass1
Private myProperty1 As Integer
Public Property MyProperty() As Integer
Get
Return myProperty1
End Get
Set(ByVal Value As Integer)
myProperty1 = Value
End Set
End Property
Public Shared Sub Run()
Try
' Get a Type object corresponding to MyClass.
Dim myType As Type = GetType(MyClass1)
' Get a PropertyInfo object by passing property name and specifying BindingFlags.
Dim myPropInfo As PropertyInfo = myType.GetProperty("MyProperty", BindingFlags.Public Or BindingFlags.Instance)
' Display the Name property.
Console.WriteLine("{0} is a property of MyClass.", myPropInfo.Name)
Catch e As NullReferenceException
Console.WriteLine("MyProperty does not exist in MyClass.", e.Message.ToString())
End Try
End Sub
End Class
End Module 'Module1
Ver também
- PropertyInfo
- String
- BindingFlags
- DefaultBinder
- GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
- GetProperties(BindingFlags)
Aplica-se a
GetProperty(String, Type)
Pesquisa pelo bem público com o nome e tipo de devolução especificados.
public:
virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType);
public:
System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType);
public System.Reflection.PropertyInfo GetProperty(string name, Type returnType);
abstract member GetProperty : string * Type -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type -> System.Reflection.PropertyInfo
member this.GetProperty : string * Type -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, returnType As Type) As PropertyInfo
Parâmetros
- name
- String
A corda que contém o nome da propriedade pública a obter.
- returnType
- Type
O tipo de devolução da propriedade.
Devoluções
Um objeto que representa a propriedade pública com o nome especificado, se encontrado; caso contrário, null.
Implementações
Exceções
Encontram-se mais do que uma propriedade com o nome especificado.
name é null, ou returnType é null.
Exemplos
O exemplo seguinte define uma classe com uma propriedade e recupera o nome e o tipo da propriedade.
using System;
using System.Reflection;
class MyPropertyTypeClass
{
public string MyProperty1 { get; set; } = "Hello World.";
}
class TestClass
{
static void Main()
{
try
{
Type myType = typeof(MyPropertyTypeClass);
// Get the PropertyInfo object representing MyProperty1.
PropertyInfo myStringProperties1 = myType.GetProperty("MyProperty1", typeof(string));
Console.WriteLine("The name of the first property of MyPropertyTypeClass is {0}.",
myStringProperties1.Name);
Console.WriteLine("The type of the first property of MyPropertyTypeClass is {0}.",
myStringProperties1.PropertyType);
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException :" + e.Message);
}
catch (AmbiguousMatchException e)
{
Console.WriteLine("AmbiguousMatchException :" + e.Message);
}
catch (NullReferenceException e)
{
Console.WriteLine("Source : {0}", e.Source);
Console.WriteLine("Message : {0}", e.Message);
}
//Output:
//The name of the first property of MyPropertyTypeClass is MyProperty1.
//The type of the first property of MyPropertyTypeClass is System.String.
}
}
open System
open System.Reflection
type MyClass1() =
let mutable myMessage = "Hello World."
member _.MyProperty1
with get () =
myMessage
and set (value) =
myMessage <- value
try
let myType = typeof<MyClass1>
// Get the PropertyInfo object representing MyProperty1.
let myStringProperties1 = myType.GetProperty("MyProperty1", typeof<string>)
printfn $"The name of the first property of MyClass1 is {myStringProperties1.Name}."
printfn $"The type of the first property of MyClass1 is {myStringProperties1.PropertyType}."
with
| :? ArgumentNullException as e ->
printfn $"ArgumentNullException :{e.Message}"
| :? AmbiguousMatchException as e ->
printfn $"AmbiguousMatchException :{e.Message}"
| :? NullReferenceException as e ->
printfn $"Source : {e.Source}"
printfn $"Message : {e.Message}"
// Output:
// The name of the first property of MyClass1 is MyProperty1.
// The type of the first property of MyClass1 is System.String.
Imports System.Reflection
Class MyTypesClass
Private myMessage As [String] = "Hello World."
Public Property MyProperty1() As String
Get
Return myMessage
End Get
Set(ByVal Value As String)
myMessage = Value
End Set
End Property
End Class
Class TestClass
Shared Sub Run()
Try
Dim myType As Type = GetType(MyTypesClass)
' Get the PropertyInfo object representing MyProperty1.
Dim myStringProperties1 As PropertyInfo = myType.GetProperty("MyProperty1", GetType(String))
Console.WriteLine("The name of the first property of MyTypesClass is {0}.", myStringProperties1.Name)
Console.WriteLine("The type of the first property of MyTypesClass is {0}.", myStringProperties1.PropertyType.ToString())
Catch e As ArgumentNullException
Console.WriteLine("ArgumentNullException :" + e.Message.ToString())
Catch e As AmbiguousMatchException
Console.WriteLine("AmbiguousMatchException :" + e.Message.ToString())
Catch e As NullReferenceException
Console.WriteLine("Source : {0}", e.Source.ToString())
Console.WriteLine("Message : {0}", e.Message.ToString())
End Try
'Output:
'The name of the first property of MyTypesClass is MyProperty1.
'The type of the first property of MyTypesClass is System.String.
End Sub
End Class
Observações
Um imóvel é considerado público para reflexão se tiver pelo menos um acessor que seja público. Caso contrário, a propriedade é considerada privada, e você deve usar BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (no Visual Basic, combinar os valores usando Or) para obtê-la.
A pesquisa diferencia name maiúsculas de minúsculas. A pesquisa inclui propriedades estáticas públicas e de instância pública.
Se o current Type representa um tipo genérico construído, esse método retorna o PropertyInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.
Se o current Type representa um parâmetro type na definição de um tipo genérico ou método genérico, esse método pesquisa as propriedades da restrição de classe.
Ver também
- PropertyInfo
- String
- DefaultBinder
- GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
- GetProperties(BindingFlags)
Aplica-se a
GetProperty(String, Type[])
Pesquisa pela propriedade pública especificada cujos parâmetros correspondem aos tipos de argumentos especificados.
public:
virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, cli::array <Type ^> ^ types);
public:
System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, cli::array <Type ^> ^ types);
public System.Reflection.PropertyInfo GetProperty(string name, Type[] types);
abstract member GetProperty : string * Type[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type[] -> System.Reflection.PropertyInfo
member this.GetProperty : string * Type[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, types As Type()) As PropertyInfo
Parâmetros
- name
- String
A corda que contém o nome da propriedade pública a obter.
- types
- Type[]
Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para a propriedade indexada a obter.
-ou-
Um array vazio do tipo Type (isto é, Tipo[] tipos = novo Tipo[0]) para obter uma propriedade que não está indexada.
Devoluções
Um objeto que representa a propriedade pública cujos parâmetros correspondem aos tipos de argumento especificados, se encontrados; caso contrário, null.
Implementações
Exceções
Encontra-se mais do que uma propriedade com o nome especificado e correspondendo aos tipos de argumentos especificados.
types é multidimensional.
Um elemento de types é null.
Exemplos
O exemplo seguinte recupera o Type objeto de uma classe definida pelo utilizador, recupera a propriedade dessa classe e apresenta o nome e o tipo da propriedade conforme especificado pelos argumentos passados a GetProperty.
using System;
using System.Reflection;
class MyClass3
{
private readonly int[,] _myArray = { { 1, 2 }, { 3, 4 } };
// Declare an indexer.
public int this[int i, int j]
{
get
{
return _myArray[i, j];
}
set
{
_myArray[i, j] = value;
}
}
}
public class MyTypeClass3
{
public static void Main(string[] args)
{
try
{
// Get the Type object.
Type myType = typeof(MyClass3);
Type[] myTypeArr = new Type[2];
// Create an instance of a Type array.
myTypeArr.SetValue(typeof(int), 0);
myTypeArr.SetValue(typeof(int), 1);
// Get the PropertyInfo object for the indexed property Item, which has two integer parameters.
PropertyInfo myPropInfo = myType.GetProperty("Item", myTypeArr);
// Display the property.
Console.WriteLine("The {0} property exists in MyClass3.",
myPropInfo.ToString());
}
catch (NullReferenceException e)
{
Console.WriteLine("An exception occurred.");
Console.WriteLine("Source : {0}", e.Source);
Console.WriteLine("Message : {0}", e.Message);
}
}
}
open System
type MyClass1() =
let myArray = array2D [[1; 2]; [3; 4]]
// Declare an indexed property.
member _.Item
with get (i, j) =
myArray[i, j]
and set (i, j) value =
myArray[i, j] <- value
try
// Get the Type object.
let myType = typeof<MyClass1>
let myTypeArr = Array.zeroCreate<Type> 2
// Create an instance of a Type array.
myTypeArr.SetValue(typeof<int>, 0)
myTypeArr.SetValue(typeof<int>, 1)
// Get the PropertyInfo object for the indexed property Item, which has two integer parameters.
let myPropInfo = myType.GetProperty("Item", myTypeArr)
// Display the property.
printfn $"The {myPropInfo} property exists in MyClass1."
with :? NullReferenceException as e ->
printfn "An exception occurred."
printfn $"Source : {e.Source}"
printfn $"Message : {e.Message}"
Imports System.Reflection
Module Module3
Class MyClass3
Private myArray As Integer(,) = {{1, 2}, {3, 4}}
' Declare an indexer.
Default Public Property Item(ByVal i As Integer, ByVal j As Integer) As Integer
Get
Return myArray(i, j)
End Get
Set(ByVal Value As Integer)
myArray(i, j) = Value
End Set
End Property
End Class
Public Class MyTypeClass3
Public Shared Sub Run()
Try
' Get the Type Object.
Dim myType As Type = GetType(MyClass3)
Dim myTypeArr(1) As Type
' Create an instance of a Type array.
myTypeArr.SetValue(GetType(Integer), 0)
myTypeArr.SetValue(GetType(Integer), 1)
' Get the PropertyInfo object for the indexed property Item, which has two integer parameters.
Dim myPropInfo As PropertyInfo = myType.GetProperty("Item", myTypeArr)
' Display the property.
Console.WriteLine("The {0} property exists in MyClass3.", myPropInfo.ToString())
Catch e As NullReferenceException
Console.WriteLine("An exception occurred.")
Console.WriteLine("Source : {0}", e.Source.ToString())
Console.WriteLine("Message : {0}", e.Message.ToString())
End Try
End Sub
End Class
End Module 'Module3
Observações
Um imóvel é considerado público para reflexão se tiver pelo menos um acessor que seja público. Caso contrário, a propriedade é considerada privada, e você deve usar BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (no Visual Basic, combinar os valores usando Or) para obtê-la.
A pesquisa diferencia name maiúsculas de minúsculas. A pesquisa inclui propriedades estáticas públicas e de instância pública.
Se o current Type representa um tipo genérico construído, esse método retorna o PropertyInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.
Se o current Type representa um parâmetro type na definição de um tipo genérico ou método genérico, esse método pesquisa as propriedades da restrição de classe.
Ver também
- PropertyInfo
- String
- DefaultBinder
- GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
- GetProperties(BindingFlags)
Aplica-se a
GetProperty(String, Type, Type[])
Pesquisa pela propriedade pública especificada cujos parâmetros correspondem aos tipos de argumentos especificados.
public:
virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types);
public:
System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types);
public System.Reflection.PropertyInfo GetProperty(string name, Type returnType, Type[] types);
abstract member GetProperty : string * Type * Type[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type * Type[] -> System.Reflection.PropertyInfo
member this.GetProperty : string * Type * Type[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, returnType As Type, types As Type()) As PropertyInfo
Parâmetros
- name
- String
A corda que contém o nome da propriedade pública a obter.
- returnType
- Type
O tipo de devolução da propriedade.
- types
- Type[]
Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para a propriedade indexada a obter.
-ou-
Um array vazio do tipo Type (isto é, Tipo[] tipos = novo Tipo[0]) para obter uma propriedade que não está indexada.
Devoluções
Um objeto que representa a propriedade pública cujos parâmetros correspondem aos tipos de argumento especificados, se encontrados; caso contrário, null.
Implementações
Exceções
Encontra-se mais do que uma propriedade com o nome especificado e correspondendo aos tipos de argumentos especificados.
types é multidimensional.
Um elemento de types é null.
Observações
Um imóvel é considerado público para reflexão se tiver pelo menos um acessor que seja público. Caso contrário, a propriedade é considerada privada, e você deve usar BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (no Visual Basic, combinar os valores usando Or) para obtê-la.
A pesquisa diferencia name maiúsculas de minúsculas. A pesquisa inclui propriedades estáticas públicas e de instância pública.
Se o current Type representa um tipo genérico construído, esse método retorna o PropertyInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.
Se o current Type representa um parâmetro type na definição de um tipo genérico ou método genérico, esse método pesquisa as propriedades da restrição de classe.
Ver também
- PropertyInfo
- String
- DefaultBinder
- GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
- GetProperties(BindingFlags)
Aplica-se a
GetProperty(String, Type, Type[], ParameterModifier[])
Pesquisa pela propriedade pública especificada cujos parâmetros correspondem aos tipos de argumentos e modificadores especificados.
public:
virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.PropertyInfo GetProperty(string name, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers);
abstract member GetProperty : string * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
member this.GetProperty : string * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, returnType As Type, types As Type(), modifiers As ParameterModifier()) As PropertyInfo
Parâmetros
- name
- String
A corda que contém o nome da propriedade pública a obter.
- returnType
- Type
O tipo de devolução da propriedade.
- types
- Type[]
Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para a propriedade indexada a obter.
-ou-
Um array vazio do tipo Type (isto é, Tipo[] tipos = novo Tipo[0]) para obter uma propriedade que não está indexada.
- modifiers
- ParameterModifier[]
Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. O binder padrão não processa este parâmetro.
Devoluções
Um objeto que represente a propriedade pública que corresponda aos requisitos especificados, se encontrado; caso contrário, null.
Implementações
Exceções
Mais do que uma propriedade é encontrada com o nome especificado e corresponde aos tipos de argumentos e modificadores especificados.
types é multidimensional.
-ou-
modifiers é multidimensional.
-ou-
types e modifiers não têm o mesmo comprimento.
Um elemento de types é null.
Exemplos
O exemplo seguinte obtém um Type objeto correspondente a MyPropertyClass, e a propriedade indexada desta classe é recuperada usando os argumentos passados ao GetProperty método.
using System;
using System.Reflection;
public class MyPropertyClass
{
private readonly int [,] _myPropertyArray = new int[10,10];
// Declare an indexer.
public int this [int i,int j]
{
get
{
return _myPropertyArray[i,j];
}
set
{
_myPropertyArray[i,j] = value;
}
}
}
public class MyTypeClass
{
public static void Main()
{
try
{
Type myType=typeof(MyPropertyClass);
Type[] myTypeArray = new Type[2];
// Create an instance of the Type array representing the number, order
// and type of the parameters for the property.
myTypeArray.SetValue(typeof(int),0);
myTypeArray.SetValue(typeof(int),1);
// Search for the indexed property whose parameters match the
// specified argument types and modifiers.
PropertyInfo myPropertyInfo = myType.GetProperty("Item",
typeof(int),myTypeArray,null);
Console.WriteLine(myType.FullName + "." + myPropertyInfo.Name +
" has a property type of " + myPropertyInfo.PropertyType);
}
catch(Exception ex)
{
Console.WriteLine("An exception occurred " + ex.Message);
}
}
}
open System
type MyPropertyClass() =
let myPropertyArray = Array2D.zeroCreate<int> 10 10
// Declare an indexed property.
member _.Item
with get (i, j) =
myPropertyArray[i, j]
and set (i, j) value =
myPropertyArray[i, j] <- value
try
let myType = typeof<MyPropertyClass>
let myTypeArray = Array.zeroCreate<Type> 2
// Create an instance of the Type array representing the number, order
// and type of the parameters for the property.
myTypeArray.SetValue(typeof<int>, 0)
myTypeArray.SetValue(typeof<int>, 1)
// Search for the indexed property whose parameters match the
// specified argument types and modifiers.
let myPropertyInfo = myType.GetProperty("Item", typeof<int>, myTypeArray, null)
printfn $"{myType.FullName}.{myPropertyInfo.Name} has a property type of {myPropertyInfo.PropertyType}"
with ex ->
printfn $"An exception occurred {ex.Message}"
Imports System.Reflection
Public Class MyPropertyClass
Private myPropertyArray(9, 9) As Integer
' Declare an indexer.
Default Public Property Item(ByVal i As Integer, ByVal j As Integer) As Integer
Get
Return myPropertyArray(i, j)
End Get
Set(ByVal Value As Integer)
myPropertyArray(i, j) = Value
End Set
End Property
End Class
Public Class MyTypeClass21
Public Shared Sub Run()
Try
Dim myType As Type = GetType(MyPropertyClass)
Dim myTypeArray(1) As Type
' Create an instance of a Type array representing the number, order
' and type of the parameters for the property.
myTypeArray.SetValue(GetType(Integer), 0)
myTypeArray.SetValue(GetType(Integer), 1)
' Search for the indexed property whose parameters match the
' specified argument types and modifiers.
Dim myPropertyInfo As PropertyInfo = myType.GetProperty("Item",
GetType(Integer), myTypeArray, Nothing)
Console.WriteLine(myType.FullName + "." + myPropertyInfo.Name +
" has a property type of " + myPropertyInfo.PropertyType.ToString())
Catch ex As Exception
Console.WriteLine("An exception occurred " + ex.Message.ToString())
End Try
End Sub
End Class
Observações
Um imóvel é considerado público para reflexão se tiver pelo menos um acessor que seja público. Caso contrário, a propriedade é considerada privada, e você deve usar BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (no Visual Basic, combinar os valores usando Or) para obtê-la.
Embora o fichário padrão não processe ParameterModifier (o modifiers parâmetro), você pode usar a classe abstrata System.Reflection.Binder para escrever um fichário personalizado que processa modifiers.
ParameterModifier é utilizado apenas ao fazer chamadas através da interoperabilidade COM, e apenas os parâmetros que são passados por referência são tratados.
A pesquisa diferencia name maiúsculas de minúsculas. A pesquisa inclui propriedades estáticas públicas e de instância pública.
Se o current Type representa um tipo genérico construído, esse método retorna o PropertyInfo com os parâmetros type substituídos pelos argumentos de tipo apropriados.
Se o current Type representa um parâmetro type na definição de um tipo genérico ou método genérico, esse método pesquisa as propriedades da restrição de classe.
Ver também
- PropertyInfo
- String
- DefaultBinder
- ParameterModifier
- GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
- GetProperties(BindingFlags)
Aplica-se a
GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
Procura a propriedade especificada cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de ligação especificadas.
public:
virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, Type ^ returnType, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.PropertyInfo GetProperty(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers);
abstract member GetProperty : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, bindingAttr As BindingFlags, binder As Binder, returnType As Type, types As Type(), modifiers As ParameterModifier()) As PropertyInfo
Parâmetros
- name
- String
A cadeia que contém o nome da propriedade a obter.
- bindingAttr
- BindingFlags
Uma combinação bit a bit dos valores de enumeração que especifica como a pesquisa é realizada.
-ou-
Default para regressar null.
- binder
- Binder
Um objeto que define um conjunto de propriedades e permite a ligação, que pode envolver a seleção de um método sobrecarregado, a coerção dos tipos de argumentos e a invocação de um membro através da reflexão.
-ou-
Uma referência nula (Nothing em Visual Basic), para usar o DefaultBinder.
- returnType
- Type
O tipo de devolução da propriedade.
- types
- Type[]
Um array de Type objetos que representa o número, ordem e tipo dos parâmetros para a propriedade indexada a obter.
-ou-
Um array vazio do tipo Type (isto é, Tipo[] tipos = novo Tipo[0]) para obter uma propriedade que não está indexada.
- modifiers
- ParameterModifier[]
Um array de ParameterModifier objetos que representa os atributos associados ao elemento correspondente no types array. O binder padrão não processa este parâmetro.
Devoluções
Um objeto que representa a propriedade que corresponde aos requisitos especificados, se for encontrado; caso contrário, null.
Implementações
Exceções
Mais do que uma propriedade é encontrada com o nome especificado e correspondendo às restrições de ligação especificadas.
types é multidimensional.
-ou-
modifiers é multidimensional.
-ou-
types e modifiers não têm o mesmo comprimento.
Um elemento de types é null.
Observações
Para mais informações sobre esta API, consulte Observações suplementares da API para Type.GetProperty.
Ver também
- PropertyInfo
- String
- BindingFlags
- Binder
- DefaultBinder
- ParameterModifier
- GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])
- GetProperties(BindingFlags)