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

屬性值

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. PropertyType從物件中取出屬性的值 PropertyInfo

適用於