共用方式為


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 的陣列,然後逐一查看陣列中的專案,或者您可以 PropertyInfo 呼叫 Type.GetProperty 方法並指定屬性名稱,來擷取直接代表屬性的物件。

  3. PropertyInfo 物件擷PropertyType取 屬性的值。

適用於