PropertyInfo.PropertyType 属性

定义

获取此属性的类型。

public:
 abstract property Type ^ PropertyType { Type ^ get(); };
public abstract Type PropertyType { get; }
member this.PropertyType : Type
Public MustOverride ReadOnly Property PropertyType As Type

属性值

此属性的类型。

实现

示例

以下示例定义一个具有五个 Employee 属性的类。 然后,它使用 检索表示这些属性的对象 PropertyInfo 数组,并显示每个属性的名称和类型。

using System;
using System.Reflection;

public class Employee
{
   private string _id;

   public String FirstName { get; set; }
   public String MiddleName { get; set; }
   public String LastName  { get; set; }
   public DateTime HireDate  { get; set; }

   public String ID
   {
      get { return _id; }
      set {
         if (ID.Trim().Length != 9)
            throw new ArgumentException("The ID is invalid");
         _id = value;
      }
   }
}

public class Example
{
   public static void Main()
   {
      Type t = typeof(Employee);
      Console.WriteLine("The {0} type has the following properties: ",
                        t.Name);
      foreach (var prop in t.GetProperties())
         Console.WriteLine("   {0} ({1})", prop.Name,
                           prop.PropertyType.Name);
   }
}
// The example displays the following output:
//       The Employee type has the following properties:
//          FirstName (String)
//          MiddleName (String)
//          LastName (String)
//          HireDate (DateTime)
//          ID (String)
Imports System.Reflection

Public Class Employee
   Private _id As String

   Public Property FirstName As String = String.Empty
   Public Property MiddleName As String = String.Empty
   Public Property LastName As String = String.Empty
   Public Property HireDate As Date = Date.Today

   Public Property ID As String
      Get
         Return _id
      End Get
      Set
         If ID.Trim().Length <> 9 Then _
            Throw New ArgumentException("The ID is invalid")
         _id = value
      End Set
   End Property
End Class

Module Example
   Public Sub Main()
      Dim t As Type = GetType(Employee)
      Console.WriteLine("The {0} type has the following properties: ",
                        t.Name)
      For Each prop In t.GetProperties()
         Console.WriteLine("   {0} ({1})", prop.Name,
                           prop.PropertyType.Name)
      Next
   End Sub
End Module
' The example displays the following output:
'    The Employee type has the following properties:
'       FirstName (String)
'       MiddleName (String)
'       LastName (String)
'       HireDate (DateTime)
'       ID (String)

注解

若要确定特定属性的类型,请执行以下操作:

  1. 获取一个 Type 对象,该对象表示 (包含 属性的类或结构) 的类型。 如果使用对象 (类型的实例) ,则可以调用其 GetType 方法。 否则,可以使用 C# 运算符或 Visual Basic GetType 运算符,如示例所示。

  2. 获取一个 PropertyInfo 对象,该对象表示你感兴趣的属性。 为此,可以从 方法获取所有属性Type.GetProperties的数组,然后循环访问数组中的元素,也可以通过调用 Type.GetProperty 方法并指定属性名称来直接检索PropertyInfo表示该属性的对象。

  3. PropertyInfo 对象中检索 属性的值PropertyType

适用于