Type.GetProperty Type.GetProperty Type.GetProperty Type.GetProperty Method

定义

获取当前 Type 的特定属性。Gets a specific property of the current Type.

重载

GetProperty(String) GetProperty(String) GetProperty(String) GetProperty(String)

搜索具有指定名称的公共属性。Searches for the public property with the specified name.

GetProperty(String, BindingFlags) GetProperty(String, BindingFlags) GetProperty(String, BindingFlags) GetProperty(String, BindingFlags)

使用指定的绑定约束搜索指定属性。Searches for the specified property, using the specified binding constraints.

GetProperty(String, Type) GetProperty(String, Type) GetProperty(String, Type) GetProperty(String, Type)

搜索具有指定名称和返回类型的公共属性。Searches for the public property with the specified name and return type.

GetProperty(String, Type[]) GetProperty(String, Type[]) GetProperty(String, Type[]) GetProperty(String, Type[])

搜索其参数与指定自变量类型匹配的指定公共属性。Searches for the specified public property whose parameters match the specified argument types.

GetProperty(String, Type, Type[]) GetProperty(String, Type, Type[]) GetProperty(String, Type, Type[]) GetProperty(String, Type, Type[])

搜索其参数与指定自变量类型匹配的指定公共属性。Searches for the specified public property whose parameters match the specified argument types.

GetProperty(String, Type, Type[], ParameterModifier[]) GetProperty(String, Type, Type[], ParameterModifier[]) GetProperty(String, Type, Type[], ParameterModifier[]) GetProperty(String, Type, Type[], ParameterModifier[])

搜索其参数与指定自变量类型及修饰符匹配的指定公共属性。Searches for the specified public property whose parameters match the specified argument types and modifiers.

GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

使用指定的绑定约束,搜索参数与指定的自变量类型及修饰符匹配的指定属性。Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.

GetProperty(String) GetProperty(String) GetProperty(String) GetProperty(String)

搜索具有指定名称的公共属性。Searches for the public property with the specified name.

public:
 virtual 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
Public Function GetProperty (name As String) As PropertyInfo

参数

name
String String String String

包含要获取的公共属性名的字符串。The string containing the name of the public property to get.

返回

表示具有指定名称的公共属性的对象(如果找到的话);否则为 nullAn object representing the public property with the specified name, if found; otherwise, null.

实现

异常

找到了多个具有指定名称的属性。More than one property is found with the specified name.

示例

下面的示例检索Type的用户定义的类的对象检索该类的属性,并显示属性名称。The following example retrieves the Type object of a user-defined class, retrieves a property of that class, and displays the property name.

using namespace System;
using namespace System::Reflection;
ref class MyClass
{
private:
   int myProperty;

public:

   property int MyProperty 
   {
      // Declare MyProperty.
      int get()
      {
         return myProperty;
      }

      void set( int value )
      {
         myProperty = value;
      }
   }
};

int main()
{
   try
   {
      // Get the Type object corresponding to MyClass.
      Type^ myType = MyClass::typeid;
      
      // 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 MyClass.", myPropInfo->Name );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine( "The property does not exist in MyClass. {0}", e->Message );
   }
}

using System;
using System.Reflection;

class MyClass
{
    private int myProperty;
    // Declare MyProperty.
    public int MyProperty
    {
        get
        {
            return myProperty;
        }
        set
        {
            myProperty=value;
        }
    }
}
public class MyTypeClass
{
    public static void Main(string[] args)
    {
        try
        {
            // Get the Type object corresponding to MyClass.
            Type myType=typeof(MyClass);       
            // 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 MyClass.", myPropInfo.Name);
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine("The property does not exist in MyClass." + e.Message);
        }
    }
}
Imports System
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 'MyClass1

Public Class MyTypeClass
    Public Shared Sub Main(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 propety 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 'Main
End Class 'MyTypeClass 

在内部,此属性所引用的元数据中的名称"项。Internally, this property is referred to in the metadata by the name "Item." 若要获取的任何尝试PropertyInfo使用反射必须指定此内部名称才能正确返回PropertyInfo属性。Any attempt to get PropertyInfo using reflection must specify this internal name in order to correctly return the PropertyInfo property.

注解

搜索name区分大小写。The search for name is case-sensitive. 搜索中包括公共 static 和 public 实例属性。The search includes public static and public instance properties.

如果它具有至少一个访问器,它是公共的属性被视为公共反射。A property is considered public to reflection if it has at least one accessor that is public. 否则,该属性被视为私有的并且必须使用BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (在 Visual Basic 中,将使用的值合并Or) 来获取它。Otherwise the property is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or) to get it.

如果当前Type表示构造泛型类型,此方法返回PropertyInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the PropertyInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示的类型参数的泛型类型或泛型方法定义中,在此方法搜索类约束的属性。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the properties of the class constraint.

在其中的情况下AmbiguousMatchException发生如下:Situations in which AmbiguousMatchException occurs include the following:

  • 一种类型包含两个索引的属性具有相同名称但具有不同数量的参数。A type contains two indexed properties that have the same name but different numbers of parameters. 若要解决多义性问题,请使用的重载GetProperty方法,它指定参数类型。To resolve the ambiguity, use an overload of the GetProperty method that specifies parameter types.

  • 派生的类型声明了通过使用隐藏继承的属性具有相同名称的属性new修饰符 (Shadows在 Visual Basic 中)。A derived type declares a property that hides an inherited property with the same name, by using the new modifier (Shadows in Visual Basic). 若要解决多义性问题,请使用GetProperty(String, BindingFlags)方法重载,并添加BindingFlags.DeclaredOnly标志,用于搜索限制为不会继承的成员。To resolve the ambiguity, use the GetProperty(String, BindingFlags) method overload and add the BindingFlags.DeclaredOnly flag to restrict the search to members that are not inherited.

索引器属性和默认属性Indexers and Default Properties

Visual Basic 2005Visual Basic 2005Visual C# 2005Visual C# 2005,和Visual C++ 2005Visual C++ 2005简化了用于访问索引的属性的语法,并允许一个索引的属性是其类型的默认值。, Visual C# 2005Visual C# 2005, and Visual C++ 2005Visual C++ 2005 have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. 例如,如果变量myList是指ArrayList,语法myList[3](myList(3)在 Visual Basic 中) 检索索引为 3 的元素。For example, if the variable myList refers to an ArrayList, the syntax myList[3] (myList(3) in Visual Basic) retrieves the element with the index of 3. 可以重载该属性。You can overload the property.

在C#,此功能称为索引器,不能将按名称引用。In C#, this feature is called an indexer and cannot be referred to by name. 默认情况下,C# 索引器将显示在元数据中作为名为"Item"索引属性。By default, a C# indexer appears in metadata as an indexed property named "Item". 但是,类库开发人员可以使用IndexerNameAttribute特性来更改元数据中的索引器的名称。However, a class library developer can use the IndexerNameAttribute attribute to change the name of the indexer in the metadata. 例如,String类具有名为一个索引器Chars[Range]For example, the String class has an indexer named Chars[Range]. 使用 C# 以外的语言创建的索引的属性可以具有项以外的名称以及。Indexed properties created using languages other than C# can have names other than Item, as well.

若要确定类型是否具有默认属性,请使用GetCustomAttributes(Type, Boolean)方法来测试DefaultMemberAttribute属性。To determine whether a type has a default property, use the GetCustomAttributes(Type, Boolean) method to test for the DefaultMemberAttribute attribute. 如果该类型具有DefaultMemberAttribute,则MemberName属性返回的默认属性的名称。If the type has DefaultMemberAttribute, the MemberName property returns the name of the default property.

另请参阅

GetProperty(String, BindingFlags) GetProperty(String, BindingFlags) GetProperty(String, BindingFlags) GetProperty(String, BindingFlags)

使用指定的绑定约束搜索指定属性。Searches for the specified property, using the specified binding constraints.

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

参数

name
String String String String

包含要获取的属性名的字符串。The string containing the name of the property to get.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted.

- 或 --or- 若为 Default,则返回 nullDefault to return null.

返回

表示符合指定要求的属性的对象(如果找到的话);否则为 nullAn object representing the property that matches the specified requirements, if found; otherwise, null.

实现

异常

找到多个具有指定名称的属性且属性与指定绑定约束匹配。More than one property is found with the specified name and matching the specified binding constraints.

示例

下面的示例检索用户定义的类的类型、 检索该类的属性并显示根据指定的绑定约束的属性名称。The following example retrieves the type of a user-defined class, retrieves a property of that class and displays the property name in accordance with the specified binding constraints.

using namespace System;
using namespace System::Reflection;
ref class MyClass
{
private:
   int myProperty;

public:

   property int MyProperty 
   {
      // Declare MyProperty.
      int get()
      {
         return myProperty;
      }

      void set( int value )
      {
         myProperty = value;
      }
   }
};

int main()
{
   try
   {
      // Get Type object of MyClass.
      Type^ myType = MyClass::typeid;
      
      // Get the PropertyInfo by passing the property name and specifying the BindingFlags.
      PropertyInfo^ myPropInfo = myType->GetProperty( "MyProperty", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
      
      // Display Name propety to console.
      Console::WriteLine( "{0} is a property of MyClass.", myPropInfo->Name );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine( "MyProperty does not exist in MyClass. {0}", e->Message );
   }
}

using System;
using System.Reflection;
class MyClass
{
    private int myProperty;
    // Declare MyProperty.
    public int MyProperty
    {
        get
        {
            return myProperty;
        }
        set
        {
            myProperty=value;
        }
    }
}
public class MyTypeClass
{
    public static void Main(string[] args)
    {
        try
        {
            // Get Type object of MyClass.
            Type myType=typeof(MyClass);       
            // Get the PropertyInfo by passing the property name and specifying the BindingFlags.
            PropertyInfo myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.Instance);
            // Display Name propety to console.
            Console.WriteLine("{0} is a property of MyClass.", myPropInfo.Name);
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine("MyProperty does not exist in MyClass." +e.Message);
        }
    }
}

Imports System
Imports System.Reflection
Module Module1
    Public 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
        Public Shared Sub Main()
            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 'Main
    End Class 'MyClass1
End Module 'Module1

注解

如果它具有至少一个访问器,它是公共的属性被视为公共反射。A property is considered public to reflection if it has at least one accessor that is public. 否则,该属性被视为私有的并且必须使用BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (在 Visual Basic 中,将使用的值合并Or) 来获取它。Otherwise the property is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or) to get it.

以下BindingFlags的筛选器标志可以用于定义要在搜索中包括的属性:The following BindingFlags filter flags can be used to define which properties to include in the search:

  • 您必须指定这两BindingFlags.InstanceBindingFlags.Static为了获取返回。You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • 指定BindingFlags.Public若要在搜索中包括的公共属性。Specify BindingFlags.Public to include public properties in the search.

  • 指定BindingFlags.NonPublic若要在搜索中包括非公共属性 (即私有、 内部和受保护属性)。Specify BindingFlags.NonPublic to include non-public properties (that is, private, internal, and protected properties) in the search.

  • 指定BindingFlags.FlattenHierarchy用以publicprotected层次结构; 上的静态成员private中继承的类的静态成员不包括。Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase 若要忽略大小写的nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly 若要搜索上声明属性Type,不只是继承的属性。BindingFlags.DeclaredOnly to search only the properties declared on the Type, not properties that were simply inherited.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

如果当前Type表示构造泛型类型,此方法返回PropertyInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the PropertyInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示的类型参数的泛型类型或泛型方法定义中,在此方法搜索类约束的属性。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the properties of the class constraint.

在其中的情况下AmbiguousMatchException发生如下:Situations in which AmbiguousMatchException occurs include the following:

  • 一种类型包含两个索引的属性具有相同名称但具有不同数量的参数。A type contains two indexed properties that have the same name but different numbers of parameters. 若要解决多义性问题,请使用的重载GetProperty方法,它指定参数类型。To resolve the ambiguity, use an overload of the GetProperty method that specifies parameter types.

  • 派生的类型声明一个属性,它会隐藏继承的属性具有相同的名称,使用new修饰符 (Shadows在 Visual Basic 中)。A derived type declares a property that hides an inherited property with the same name, using the new modifier (Shadows in Visual Basic). 若要解决多义性问题,包括BindingFlags.DeclaredOnly来搜索限制为不会继承的成员。To resolve the ambiguity, include BindingFlags.DeclaredOnly to restrict the search to members that are not inherited.

索引器属性和默认属性Indexers and Default Properties

Visual Basic 2005Visual Basic 2005Visual C# 2005Visual C# 2005,和Visual C++ 2005Visual C++ 2005简化了用于访问索引的属性的语法,并允许一个索引的属性是其类型的默认值。, Visual C# 2005Visual C# 2005, and Visual C++ 2005Visual C++ 2005 have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. 例如,如果变量myList是指ArrayList,语法myList[3](myList(3)在 Visual Basic 中) 检索索引为 3 的元素。For example, if the variable myList refers to an ArrayList, the syntax myList[3] (myList(3) in Visual Basic) retrieves the element with the index of 3. 可以重载该属性。You can overload the property.

在C#,此功能称为索引器,不能将按名称引用。In C#, this feature is called an indexer and cannot be referred to by name. 默认情况下,C# 索引器将显示在元数据中作为名为"Item"索引属性。By default, a C# indexer appears in metadata as an indexed property named "Item". 但是,类库开发人员可以使用IndexerNameAttribute特性来更改元数据中的索引器的名称。However, a class library developer can use the IndexerNameAttribute attribute to change the name of the indexer in the metadata. 例如,String类具有名为一个索引器Chars[Range]For example, the String class has an indexer named Chars[Range]. 使用 C# 以外的语言创建的索引的属性可以具有项以外的名称以及。Indexed properties created using languages other than C# can have names other than Item, as well.

若要确定类型是否具有默认属性,请使用GetCustomAttributes(Type, Boolean)方法来测试DefaultMemberAttribute属性。To determine whether a type has a default property, use the GetCustomAttributes(Type, Boolean) method to test for the DefaultMemberAttribute attribute. 如果该类型具有DefaultMemberAttribute,则MemberName属性返回的默认属性的名称。If the type has DefaultMemberAttribute, the MemberName property returns the name of the default property.

另请参阅

GetProperty(String, Type) GetProperty(String, Type) GetProperty(String, Type) GetProperty(String, Type)

搜索具有指定名称和返回类型的公共属性。Searches for the public property with the specified name and return type.

public:
 virtual 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
Public Function GetProperty (name As String, returnType As Type) As PropertyInfo

参数

name
String String String String

包含要获取的公共属性名的字符串。The string containing the name of the public property to get.

returnType
Type Type Type Type

属性的返回类型。The return type of the property.

返回

表示具有指定名称的公共属性的对象(如果找到的话);否则为 nullAn object representing the public property with the specified name, if found; otherwise, null.

实现

异常

找到了多个具有指定名称的属性。More than one property is found with the specified name.

namenull,或 returnTypenullname is null, or returnType is null.

示例

下面的示例定义具有一个属性的类,并检索名称和属性的类型。The following example defines a class with one property and retrieves the name and type of the property.

using namespace System;
using namespace System::Reflection;
ref class MyClass1
{
private:
   String^ myMessage;

public:

   property String^ MyProperty1 
   {
      String^ get()
      {
         return myMessage;
      }

      void set( String^ value )
      {
         myMessage = value;
      }
   }
};

int main()
{
   try
   {
      Type^ myType = MyClass1::typeid;
      
      // Get the PropertyInfo Object* representing MyProperty1.
      PropertyInfo^ myStringProperties1 = myType->GetProperty( "MyProperty1", String::typeid );
      Console::WriteLine( "The name of the first property of MyClass1 is {0}.", myStringProperties1->Name );
      Console::WriteLine( "The type of the first property of MyClass1 is {0}.", myStringProperties1->PropertyType );
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "ArgumentNullException : {0}", e->Message );
   }
   catch ( AmbiguousMatchException^ e ) 
   {
      Console::WriteLine( "AmbiguousMatchException : {0}", 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 MyClass1 is MyProperty1.
   //The type of the first property of MyClass1 is System.String.

}

using System;
using System.Reflection;

class MyClass1
{
    String myMessage="Hello World.";
    public string MyProperty1
    {
        get
        {			
            return myMessage;
        }
        set
        {
            myMessage =value;
        }			
    }
}
class TestClass
{
    static void Main()
    {
        try
        {	
            Type myType = typeof(MyClass1);
            // Get the PropertyInfo object representing MyProperty1. 
            PropertyInfo myStringProperties1 = myType.GetProperty("MyProperty1",
                typeof(string));
            Console.WriteLine("The name of the first property of MyClass1 is {0}.", myStringProperties1.Name);
            Console.WriteLine("The type of the first property of MyClass1 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 MyClass1 is MyProperty1.
	//The type of the first property of MyClass1 is System.String.
    }
}
Imports System
Imports System.Reflection
Class MyClass1
    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 'MyClass1

Class TestClass
    Shared Sub Main()
        Try
            Dim myType As Type = GetType(MyClass1)
            ' Get the PropertyInfo object representing MyProperty1. 
            Dim myStringProperties1 As PropertyInfo = myType.GetProperty("MyProperty1", GetType(String))
            Console.WriteLine("The name of the first property of MyClass1 is {0}.", myStringProperties1.Name)
            Console.WriteLine("The type of the first property of MyClass1 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 MyClass1 is MyProperty1.
	'The type of the first property of MyClass1 is System.String.

    End Sub 'Main
End Class 'TestClass

注解

如果它具有至少一个访问器,它是公共的属性被视为公共反射。A property is considered public to reflection if it has at least one accessor that is public. 否则,该属性被视为私有的并且必须使用BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (在 Visual Basic 中,将使用的值合并Or) 来获取它。Otherwise the property is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or) to get it.

搜索name区分大小写。The search for name is case-sensitive. 搜索中包括公共 static 和 public 实例属性。The search includes public static and public instance properties.

如果当前Type表示构造泛型类型,此方法返回PropertyInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the PropertyInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示的类型参数的泛型类型或泛型方法定义中,在此方法搜索类约束的属性。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the properties of the class constraint.

索引器属性和默认属性Indexers and Default Properties

Visual Basic 2005Visual Basic 2005Visual C# 2005Visual C# 2005,和Visual C++ 2005Visual C++ 2005简化了用于访问索引的属性的语法,并允许一个索引的属性是其类型的默认值。, Visual C# 2005Visual C# 2005, and Visual C++ 2005Visual C++ 2005 have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. 例如,如果变量myList是指ArrayList,语法myList[3](myList(3)在 Visual Basic 中) 检索索引为 3 的元素。For example, if the variable myList refers to an ArrayList, the syntax myList[3] (myList(3) in Visual Basic) retrieves the element with the index of 3. 可以重载该属性。You can overload the property.

在C#,此功能称为索引器,不能将按名称引用。In C#, this feature is called an indexer and cannot be referred to by name. 默认情况下,C# 索引器将显示在元数据中作为名为"Item"索引属性。By default, a C# indexer appears in metadata as an indexed property named "Item". 但是,类库开发人员可以使用IndexerNameAttribute特性来更改元数据中的索引器的名称。However, a class library developer can use the IndexerNameAttribute attribute to change the name of the indexer in the metadata. 例如,String类具有名为一个索引器Chars[Range]For example, the String class has an indexer named Chars[Range]. 使用 C# 以外的语言创建的索引的属性可以具有项以外的名称以及。Indexed properties created using languages other than C# can have names other than Item, as well.

若要确定类型是否具有默认属性,请使用GetCustomAttributes(Type, Boolean)方法来测试DefaultMemberAttribute属性。To determine whether a type has a default property, use the GetCustomAttributes(Type, Boolean) method to test for the DefaultMemberAttribute attribute. 如果该类型具有DefaultMemberAttribute,则MemberName属性返回的默认属性的名称。If the type has DefaultMemberAttribute, the MemberName property returns the name of the default property.

另请参阅

GetProperty(String, Type[]) GetProperty(String, Type[]) GetProperty(String, Type[]) GetProperty(String, Type[])

搜索其参数与指定自变量类型匹配的指定公共属性。Searches for the specified public property whose parameters match the specified argument types.

public:
 virtual 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
Public Function GetProperty (name As String, types As Type()) As PropertyInfo

参数

name
String String String String

包含要获取的公共属性名的字符串。The string containing the name of the public property to get.

types
Type[]

一个 Type 对象数组,表示要获取的索引属性的参数的数目、顺序和类型。An array of Type objects representing the number, order, and type of the parameters for the indexed property 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 property that is not indexed.

返回

表示其参数与指定参数类型匹配的公共属性的对象(如果找到的话);否则为 nullAn object representing the public property whose parameters match the specified argument types, if found; otherwise, null.

实现

异常

找到多个具有指定名称且与指定自变量类型匹配的属性。More than one property is found with the specified name and matching the specified argument types.

namenullname is null.

-or- typesnulltypes is null.

types 是多维的。types is multidimensional.

types 的元素为 nullAn element of types is null.

示例

下面的示例检索Type用户定义的类的对象检索该类的属性,并显示属性名称和属性的类型作为参数传递给指定的GetPropertyThe following example retrieves the Type object of a user-defined class, retrieves the property of that class, and displays the property name and type of the property as specified by the arguments passed to GetProperty.

using namespace System;
using namespace System::Reflection;
ref class MyClass1
{
private:
   array<int, 2>^myArray;

public:

   property int Item [int, int]
   {

      // Declare an indexer.
      int get( int i, int j )
      {
         return myArray[ i,j ];
      }

      void set( int i, int j, int value )
      {
         myArray[ i,j ] = value;
      }

   }

};

int main()
{
   try
   {
      
      // Get the Type object.
      Type^ myType = MyClass1::typeid;
      array<Type^>^myTypeArr = gcnew array<Type^>(2);
      
      // Create an instance of a Type array.
      myTypeArr->SetValue( int::typeid, 0 );
      myTypeArr->SetValue( int::typeid, 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 MyClass1.", myPropInfo );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine( "An exception occurred." );
      Console::WriteLine( "Source : {0}", e->Source );
      Console::WriteLine( "Message : {0}", e->Message );
   }

}


using System;
using System.Reflection;
class MyClass1
{         
    private 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 MyTypeClass
{
    public static void Main(string[] args)
    {
        try
        { 
            // Get the Type object.
            Type myType=typeof(MyClass1);       
            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 MyClass1.", myPropInfo.ToString());
        }           
        catch(NullReferenceException e)
        {
            Console.WriteLine("An exception occurred.");
            Console.WriteLine("Source : {0}" , e.Source);
            Console.WriteLine("Message : {0}" , e.Message);
        }
    }
}
Imports System
Imports System.Reflection

Module Module1
    Class MyClass1
        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 'MyClass1

    Public Class MyTypeClass
        Public Shared Sub Main()
            Try
                ' Get the Type Object.
                Dim myType As Type = GetType(MyClass1)
                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 MyClass1.", 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 'Main
    End Class 'MyTypeClass
End Module 'Module1

注解

如果它具有至少一个访问器,它是公共的属性被视为公共反射。A property is considered public to reflection if it has at least one accessor that is public. 否则,该属性被视为私有的并且必须使用BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (在 Visual Basic 中,将使用的值合并Or) 来获取它。Otherwise the property is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or) to get it.

搜索name区分大小写。The search for name is case-sensitive. 搜索中包括公共 static 和 public 实例属性。The search includes public static and public instance properties.

如果当前Type表示构造泛型类型,此方法返回PropertyInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the PropertyInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示的类型参数的泛型类型或泛型方法定义中,在此方法搜索类约束的属性。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the properties of the class constraint.

索引器属性和默认属性Indexers and Default Properties

Visual Basic 2005Visual Basic 2005Visual C# 2005Visual C# 2005,和Visual C++ 2005Visual C++ 2005简化了用于访问索引的属性的语法,并允许一个索引的属性是其类型的默认值。, Visual C# 2005Visual C# 2005, and Visual C++ 2005Visual C++ 2005 have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. 例如,如果变量myList是指ArrayList,语法myList[3](myList(3)在 Visual Basic 中) 检索索引为 3 的元素。For example, if the variable myList refers to an ArrayList, the syntax myList[3] (myList(3) in Visual Basic) retrieves the element with the index of 3. 可以重载该属性。You can overload the property.

在C#,此功能称为索引器,不能将按名称引用。In C#, this feature is called an indexer and cannot be referred to by name. 默认情况下,C# 索引器将显示在元数据中作为名为"Item"索引属性。By default, a C# indexer appears in metadata as an indexed property named "Item". 但是,类库开发人员可以使用IndexerNameAttribute特性来更改元数据中的索引器的名称。However, a class library developer can use the IndexerNameAttribute attribute to change the name of the indexer in the metadata. 例如,String类具有名为一个索引器Chars[Range]For example, the String class has an indexer named Chars[Range]. 使用 C# 以外的语言创建的索引的属性可以具有项以外的名称以及。Indexed properties created using languages other than C# can have names other than Item, as well.

若要确定类型是否具有默认属性,请使用GetCustomAttributes(Type, Boolean)方法来测试DefaultMemberAttribute属性。To determine whether a type has a default property, use the GetCustomAttributes(Type, Boolean) method to test for the DefaultMemberAttribute attribute. 如果该类型具有DefaultMemberAttribute,则MemberName属性返回的默认属性的名称。If the type has DefaultMemberAttribute, the MemberName property returns the name of the default property.

另请参阅

GetProperty(String, Type, Type[]) GetProperty(String, Type, Type[]) GetProperty(String, Type, Type[]) GetProperty(String, Type, Type[])

搜索其参数与指定自变量类型匹配的指定公共属性。Searches for the specified public property whose parameters match the specified argument types.

public:
 virtual 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
Public Function GetProperty (name As String, returnType As Type, types As Type()) As PropertyInfo

参数

name
String String String String

包含要获取的公共属性名的字符串。The string containing the name of the public property to get.

returnType
Type Type Type Type

属性的返回类型。The return type of the property.

types
Type[]

一个 Type 对象数组,表示要获取的索引属性的参数的数目、顺序和类型。An array of Type objects representing the number, order, and type of the parameters for the indexed property 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 property that is not indexed.

返回

表示其参数与指定参数类型匹配的公共属性的对象(如果找到的话);否则为 nullAn object representing the public property whose parameters match the specified argument types, if found; otherwise, null.

实现

异常

找到多个具有指定名称且与指定自变量类型匹配的属性。More than one property is found with the specified name and matching the specified argument types.

namenullname is null.

- 或 --or- typesnulltypes is null.

types 是多维的。types is multidimensional.

types 的元素为 nullAn element of types is null.

注解

如果它具有至少一个访问器,它是公共的属性被视为公共反射。A property is considered public to reflection if it has at least one accessor that is public. 否则,该属性被视为私有的并且必须使用BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (在 Visual Basic 中,将使用的值合并Or) 来获取它。Otherwise the property is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or) to get it.

搜索name区分大小写。The search for name is case-sensitive. 搜索中包括公共 static 和 public 实例属性。The search includes public static and public instance properties.

如果当前Type表示构造泛型类型,此方法返回PropertyInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the PropertyInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示的类型参数的泛型类型或泛型方法定义中,在此方法搜索类约束的属性。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the properties of the class constraint.

索引器属性和默认属性Indexers and Default Properties

Visual Basic 2005Visual Basic 2005Visual C# 2005Visual C# 2005,和Visual C++ 2005Visual C++ 2005简化了用于访问索引的属性的语法,并允许一个索引的属性是其类型的默认值。, Visual C# 2005Visual C# 2005, and Visual C++ 2005Visual C++ 2005 have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. 例如,如果变量myList是指ArrayList,语法myList[3](myList(3)在 Visual Basic 中) 检索索引为 3 的元素。For example, if the variable myList refers to an ArrayList, the syntax myList[3] (myList(3) in Visual Basic) retrieves the element with the index of 3. 可以重载该属性。You can overload the property.

在C#,此功能称为索引器,不能将按名称引用。In C#, this feature is called an indexer and cannot be referred to by name. 默认情况下,C# 索引器将显示在元数据中作为名为"Item"索引属性。By default, a C# indexer appears in metadata as an indexed property named "Item". 但是,类库开发人员可以使用IndexerNameAttribute特性来更改元数据中的索引器的名称。However, a class library developer can use the IndexerNameAttribute attribute to change the name of the indexer in the metadata. 例如,String类具有名为一个索引器Chars[Range]For example, the String class has an indexer named Chars[Range]. 使用 C# 以外的语言创建的索引的属性可以具有项以外的名称以及。Indexed properties created using languages other than C# can have names other than Item, as well.

若要确定类型是否具有默认属性,请使用GetCustomAttributes(Type, Boolean)方法来测试DefaultMemberAttribute属性。To determine whether a type has a default property, use the GetCustomAttributes(Type, Boolean) method to test for the DefaultMemberAttribute attribute. 如果该类型具有DefaultMemberAttribute,则MemberName属性返回的默认属性的名称。If the type has DefaultMemberAttribute, the MemberName property returns the name of the default property.

另请参阅

GetProperty(String, Type, Type[], ParameterModifier[]) GetProperty(String, Type, Type[], ParameterModifier[]) GetProperty(String, Type, Type[], ParameterModifier[]) GetProperty(String, Type, Type[], ParameterModifier[])

搜索其参数与指定自变量类型及修饰符匹配的指定公共属性。Searches for the specified public property whose parameters match the specified argument types and modifiers.

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 (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
Public Function GetProperty (name As String, returnType As Type, types As Type(), modifiers As ParameterModifier()) As PropertyInfo

参数

name
String String String String

包含要获取的公共属性名的字符串。The string containing the name of the public property to get.

returnType
Type Type Type Type

属性的返回类型。The return type of the property.

types
Type[]

一个 Type 对象数组,表示要获取的索引属性的参数的数目、顺序和类型。An array of Type objects representing the number, order, and type of the parameters for the indexed property 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 property that is not indexed.

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.

返回

表示符合指定要求的公共属性的对象(如果找到的话);否则为 nullAn object representing the public property that matches the specified requirements, if found; otherwise, null.

实现

异常

找到多个具有指定名称且与指定参数类型和修饰符匹配的属性。More than one property is found with the specified name and matching the specified argument types and modifiers.

namenullname is null.

-or- typesnulltypes is null.

types 是多维的。types is multidimensional.

- 或 --or- modifiers 是多维的。modifiers is multidimensional.

- 或 --or- typesmodifiers 的长度不相同。types and modifiers do not have the same length.

types 的元素为 nullAn element of types is null.

示例

以下示例获取Type对象对应于MyPropertyClass,并使用传递给的参数检索此类的索引的属性GetProperty方法。The following example obtains a Type object corresponding to MyPropertyClass, and the indexed property of this class is retrieved using the arguments passed to the GetProperty method.

using namespace System;
using namespace System::Reflection;
public ref class MyPropertyClass
{
private:
   array<int, 2>^ myPropertyArray;

public:

   property int Item [int, int]
   {
      // Declare an indexer.
      int get( int i, int j )
      {
         return myPropertyArray[ i,j ];
      }

      void set( int i, int j, int value )
      {
         myPropertyArray[ i,j ] = value;
      }

   }

};

int main()
{
   try
   {
      Type^ myType = MyPropertyClass::typeid;
      array<Type^>^myTypeArray = gcnew array<Type^>(2);
      
      // Create an instance of the Type array representing the number, order
      // and type of the parameters for the property.
      myTypeArray->SetValue( int::typeid, 0 );
      myTypeArray->SetValue( int::typeid, 1 );
      
      // Search for the indexed property whose parameters match the
      // specified argument types and modifiers.
      PropertyInfo^ myPropertyInfo = myType->GetProperty( "Item", int::typeid, myTypeArray, nullptr );
      Console::WriteLine( "{0}.{1} has a property type of {2}", myType->FullName, myPropertyInfo->Name, myPropertyInfo->PropertyType );
   }
   catch ( Exception^ ex ) 
   {
      Console::WriteLine( "An exception occurred {0}", ex->Message );
   }

}

using System;
using System.Reflection;
public class MyPropertyClass
{
    private 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);
        }
    }
}
Imports System
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 'MyPropertyClass

Public Class MyTypeClass
    Public Shared Sub Main()
        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 'Main
End Class 'MyTypeClass

注解

如果它具有至少一个访问器,它是公共的属性被视为公共反射。A property is considered public to reflection if it has at least one accessor that is public. 否则,该属性被视为私有的并且必须使用BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (在 Visual Basic 中,将使用的值合并Or) 来获取它。Otherwise the property is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or) to get it.

尽管默认联编程序不会处理ParameterModifier(modifiers参数),您可以使用抽象System.Reflection.Binder类以编写的自定义联编程序modifiersAlthough 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.

搜索name区分大小写。The search for name is case-sensitive. 搜索中包括公共 static 和 public 实例属性。The search includes public static and public instance properties.

如果当前Type表示构造泛型类型,此方法返回PropertyInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the PropertyInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示的类型参数的泛型类型或泛型方法定义中,在此方法搜索类约束的属性。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the properties of the class constraint.

索引器属性和默认属性Indexers and Default Properties

Visual Basic 2005Visual Basic 2005Visual C# 2005Visual C# 2005,和Visual C++ 2005Visual C++ 2005简化了用于访问索引的属性的语法,并允许一个索引的属性是其类型的默认值。, Visual C# 2005Visual C# 2005, and Visual C++ 2005Visual C++ 2005 have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. 例如,如果变量myList是指ArrayList,语法myList[3](myList(3)在 Visual Basic 中) 检索索引为 3 的元素。For example, if the variable myList refers to an ArrayList, the syntax myList[3] (myList(3) in Visual Basic) retrieves the element with the index of 3. 可以重载该属性。You can overload the property.

在C#,此功能称为索引器,不能将按名称引用。In C#, this feature is called an indexer and cannot be referred to by name. 默认情况下,C# 索引器将显示在元数据中作为名为"Item"索引属性。By default, a C# indexer appears in metadata as an indexed property named "Item". 但是,类库开发人员可以使用IndexerNameAttribute特性来更改元数据中的索引器的名称。However, a class library developer can use the IndexerNameAttribute attribute to change the name of the indexer in the metadata. 例如,String类具有名为一个索引器Chars[Range]For example, the String class has an indexer named Chars[Range]. 使用 C# 以外的语言创建的索引的属性可以具有项以外的名称以及。Indexed properties created using languages other than C# can have names other than Item, as well.

若要确定类型是否具有默认属性,请使用GetCustomAttributes(Type, Boolean)方法来测试DefaultMemberAttribute属性。To determine whether a type has a default property, use the GetCustomAttributes(Type, Boolean) method to test for the DefaultMemberAttribute attribute. 如果该类型具有DefaultMemberAttribute,则MemberName属性返回的默认属性的名称。If the type has DefaultMemberAttribute, the MemberName property returns the name of the default property.

另请参阅

GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

使用指定的绑定约束,搜索参数与指定的自变量类型及修饰符匹配的指定属性。Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.

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

参数

name
String String String String

包含要获取的属性名的字符串。The string containing the name of the property to get.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted.

- 或 --or- 若为 Default,则返回 nullDefault to return null.

binder
Binder Binder 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.

returnType
Type Type Type Type

属性的返回类型。The return type of the property.

types
Type[]

一个 Type 对象数组,表示要获取的索引属性的参数的数目、顺序和类型。An array of Type objects representing the number, order, and type of the parameters for the indexed property 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 property that is not indexed.

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.

返回

表示符合指定要求的属性的对象(如果找到的话);否则为 nullAn object representing the property that matches the specified requirements, if found; otherwise, null.

实现

异常

找到多个具有指定名称的属性且属性与指定绑定约束匹配。More than one property is found with the specified name and matching the specified binding constraints.

namenullname is null.

-or- typesnulltypes is null.

types 是多维的。types is multidimensional.

- 或 --or- modifiers 是多维的。modifiers is multidimensional.

- 或 --or- typesmodifiers 的长度不相同。types and modifiers do not have the same length.

types 的元素为 nullAn element of types is null.

注解

如果它具有至少一个访问器,它是公共的属性被视为公共反射。A property is considered public to reflection if it has at least one accessor that is public. 否则,该属性被视为私有的并且必须使用BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (在 Visual Basic 中,将使用的值合并Or) 来获取它。Otherwise the property is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or) to get it.

尽管默认联编程序不会处理ParameterModifier(modifiers参数),您可以使用抽象System.Reflection.Binder类以编写的自定义联编程序modifiersAlthough 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.

下表显示了返回通过基类的成员Get方法反射的类型上时。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成员类型Member Type StaticStatic 非静态Non-Static
构造函数Constructor NoNo NoNo
字段Field NoNo 可以。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 NoNo 可以。Yes. 方法 (包括虚拟和非虚拟) 可以隐藏通过名称或按名称和签名隐藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
嵌套的类型Nested Type NoNo NoNo
PropertyProperty 不适用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.
  1. 按名称和签名隐藏会考虑所有的签名,包括自定义修饰符,部分返回类型、 参数类型、 标记和非托管调用约定。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.

  2. 为反射,属性和事件均由名称和签名隐藏。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.

  3. 自定义特性不是通用类型系统的一部分。Custom attributes are not part of the common type system.

以下BindingFlags的筛选器标志可以用于定义要在搜索中包括的属性:The following BindingFlags filter flags can be used to define which properties to include in the search:

  • 您必须指定这两BindingFlags.InstanceBindingFlags.Static为了获取返回。You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • 指定BindingFlags.Public若要在搜索中包括的公共属性。Specify BindingFlags.Public to include public properties in the search.

  • 指定BindingFlags.NonPublic若要在搜索中包括非公共属性 (即私有、 内部和受保护属性)。Specify BindingFlags.NonPublic to include non-public properties (that is, private, internal, and protected properties) in the search.

  • 指定BindingFlags.FlattenHierarchy用以publicprotected层次结构; 上的静态成员private中继承的类的静态成员不包括。Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase 若要忽略大小写的nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly 若要搜索上声明属性Type,不只是继承的属性。BindingFlags.DeclaredOnly to search only the properties declared on the Type, not properties that were simply inherited.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

如果当前Type表示构造泛型类型,此方法返回PropertyInfo具有类型参数替换为适当的类型参数。If the current Type represents a constructed generic type, this method returns the PropertyInfo with the type parameters replaced by the appropriate type arguments.

如果当前Type表示的类型参数的泛型类型或泛型方法定义中,在此方法搜索类约束的属性。If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the properties of the class constraint.

索引器属性和默认属性Indexers and Default Properties

Visual Basic 2005Visual Basic 2005Visual C# 2005Visual C# 2005,和Visual C++ 2005Visual C++ 2005简化了用于访问索引的属性的语法,并允许一个索引的属性是其类型的默认值。, Visual C# 2005Visual C# 2005, and Visual C++ 2005Visual C++ 2005 have simplified syntax for accessing indexed properties and allow one indexed property to be a default for its type. 例如,如果变量myList是指ArrayList,语法myList[3](myList(3)在 Visual Basic 中) 检索索引为 3 的元素。For example, if the variable myList refers to an ArrayList, the syntax myList[3] (myList(3) in Visual Basic) retrieves the element with the index of 3. 可以重载该属性。You can overload the property.

在C#,此功能称为索引器,不能将按名称引用。In C#, this feature is called an indexer and cannot be referred to by name. 默认情况下,C# 索引器将显示在元数据中作为名为"Item"索引属性。By default, a C# indexer appears in metadata as an indexed property named "Item". 但是,类库开发人员可以使用IndexerNameAttribute特性来更改元数据中的索引器的名称。However, a class library developer can use the IndexerNameAttribute attribute to change the name of the indexer in the metadata. 例如,String类具有名为一个索引器Chars[Range]For example, the String class has an indexer named Chars[Range]. 使用 C# 以外的语言创建的索引的属性可以具有项以外的名称以及。Indexed properties created using languages other than C# can have names other than Item, as well.

若要确定类型是否具有默认属性,请使用GetCustomAttributes(Type, Boolean)方法来测试DefaultMemberAttribute属性。To determine whether a type has a default property, use the GetCustomAttributes(Type, Boolean) method to test for the DefaultMemberAttribute attribute. 如果该类型具有DefaultMemberAttribute,则MemberName属性返回的默认属性的名称。If the type has DefaultMemberAttribute, the MemberName property returns the name of the default property.

另请参阅

适用于