Type.GetProperty 方法

定义

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

重载

GetProperty(String)

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

GetProperty(String, BindingFlags)

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

GetProperty(String, Type)

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

GetProperty(String, Type[])

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

GetProperty(String, Type, Type[])

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

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[])

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

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

包含要获取的公共属性名的字符串。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.

namenullname is null.

示例

下面的示例检索用户定义类的 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.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 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
End Class

在内部,在元数据中,名称为 "Item"。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. 搜索包括公共静态和公共实例属性。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 表示构造泛型类型,则此方法将返回类型参数替换为相应类型参数的 PropertyInfoIf 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# 2005Visual 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] (Visual Basic 中的myList(3))检索索引为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[Int32]的索引器。For example, the String class has an indexer named Chars[Int32]. 使用以外的其他语言创建的C#索引属性也可以包含除 Item 以外的其他名称。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)

使用指定的绑定约束搜索指定属性。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

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

bindingAttr
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.

namenullname is null.

示例

下面的示例检索用户定义的类的类型,检索该类的属性,并根据指定的绑定约束显示属性名称。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.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
    End Class
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.StaticYou 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 忽略 name的大小写。BindingFlags.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 表示构造泛型类型,则此方法将返回类型参数替换为相应类型参数的 PropertyInfoIf 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# 2005Visual 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] (Visual Basic 中的myList(3))检索索引为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[Int32]的索引器。For example, the String class has an indexer named Chars[Int32]. 使用以外的其他语言创建的C#索引属性也可以包含除 Item 以外的其他名称。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)

搜索具有指定名称和返回类型的公共属性。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

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

returnType
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.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

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
End Class

注解

如果某个属性至少具有一个公共访问器,则该属性将被视为 "公共"。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. 搜索包括公共静态和公共实例属性。The search includes public static and public instance properties.

如果当前 Type 表示构造泛型类型,则此方法将返回类型参数替换为相应类型参数的 PropertyInfoIf 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# 2005Visual 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] (Visual Basic 中的myList(3))检索索引为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[Int32]的索引器。For example, the String class has an indexer named Chars[Int32]. 使用以外的其他语言创建的C#索引属性也可以包含除 Item 以外的其他名称。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[])

搜索其参数与指定自变量类型匹配的指定公共属性。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

包含要获取的公共属性名的字符串。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 对象、检索该类的属性,并显示由传递给 GetProperty的参数指定的属性的属性名称和类型。The 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.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

    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
    End Class
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. 搜索包括公共静态和公共实例属性。The search includes public static and public instance properties.

如果当前 Type 表示构造泛型类型,则此方法将返回类型参数替换为相应类型参数的 PropertyInfoIf 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# 2005Visual 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] (Visual Basic 中的myList(3))检索索引为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[Int32]的索引器。For example, the String class has an indexer named Chars[Int32]. 使用以外的其他语言创建的C#索引属性也可以包含除 Item 以外的其他名称。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[])

搜索其参数与指定自变量类型匹配的指定公共属性。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

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

returnType
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. 搜索包括公共静态和公共实例属性。The search includes public static and public instance properties.

如果当前 Type 表示构造泛型类型,则此方法将返回类型参数替换为相应类型参数的 PropertyInfoIf 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# 2005Visual 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] (Visual Basic 中的myList(3))检索索引为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[Int32]的索引器。For example, the String class has an indexer named Chars[Int32]. 使用以外的其他语言创建的C#索引属性也可以包含除 Item 以外的其他名称。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[])

搜索其参数与指定自变量类型及修饰符匹配的指定公共属性。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

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

returnType
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.

示例

下面的示例获取对应于 MyPropertyClassType 对象,并使用传递给 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.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 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
End Class

注解

如果某个属性至少具有一个公共访问器,则该属性将被视为 "公共"。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.

尽管默认联编程序不处理 ParameterModifiermodifiers 参数),但你可以使用 abstract System.Reflection.Binder 类编写处理 modifiers的自定义联编程序。Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. 仅当通过 COM 互操作进行调用时才使用 ParameterModifier,且仅处理通过引用传递的参数。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. 搜索包括公共静态和公共实例属性。The search includes public static and public instance properties.

如果当前 Type 表示构造泛型类型,则此方法将返回类型参数替换为相应类型参数的 PropertyInfoIf 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# 2005Visual 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] (Visual Basic 中的myList(3))检索索引为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[Int32]的索引器。For example, the String class has an indexer named Chars[Int32]. 使用以外的其他语言创建的C#索引属性也可以包含除 Item 以外的其他名称。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[])

使用指定的绑定约束,搜索参数与指定的自变量类型及修饰符匹配的指定属性。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

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

bindingAttr
BindingFlags

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

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

binder
Binder

一个对象,该对象定义一组属性并启用绑定,而绑定可能涉及选择重载方法、强制参数类型和通过反射调用成员。An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

-or- 要使用 Nothing 的空引用(在 Visual Basic 中为 DefaultBinder)。A null reference (Nothing in Visual Basic), to use the DefaultBinder.

returnType
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.

尽管默认联编程序不处理 ParameterModifiermodifiers 参数),但你可以使用 abstract System.Reflection.Binder 类编写处理 modifiers的自定义联编程序。Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. 仅当通过 COM 互操作进行调用时才使用 ParameterModifier,且仅处理通过引用传递的参数。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
属性Property 不适用Not applicable 通用类型系统规则是指继承与实现属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为隐藏的名称和签名。Reflection treats properties as hide-by-name-and-signature. 请参阅下面的注释2。See note 2 below.
  1. 按名称和签名隐藏将考虑签名的所有部分,包括自定义修饰符、返回类型、参数类型、个 sentinel 和非托管调用约定。Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. 这是二进制比较。This is a binary comparison.

  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.StaticYou 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 忽略 name的大小写。BindingFlags.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 表示构造泛型类型,则此方法将返回类型参数替换为相应类型参数的 PropertyInfoIf 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# 2005Visual 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] (Visual Basic 中的myList(3))检索索引为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[Int32]的索引器。For example, the String class has an indexer named Chars[Int32]. 使用以外的其他语言创建的C#索引属性也可以包含除 Item 以外的其他名称。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.

另请参阅

适用于