PropertyInfo.PropertyType 屬性

定義

取得這個屬性的型別。

C#
public abstract Type PropertyType { get; }

屬性值

此屬性的類型。

實作

範例

下列範例會定義具有五個 Employee 屬性的類別。 然後,它會使用 擷取代表這些屬性的物件 PropertyInfo 數位,並顯示每個屬性的名稱和類型。

C#
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)

備註

若要判斷特定屬性的類型,請執行下列動作:

  1. Type取得物件,表示包含 屬性之類別或結構) (型別。 如果您要使用物件 (類型實例) ,您可以呼叫其 GetType 方法。 否則,您可以使用 C# 運算符或 Visual Basic GetType 運算符,如範例所示。

  2. PropertyInfo取得物件,表示您感興趣的屬性。 您可以從 方法取得所有屬性 Type.GetProperties 的陣列,然後逐一查看陣列中的專案,或者您可以 PropertyInfo 呼叫 Type.GetProperty 方法並指定屬性名稱,來擷取直接代表屬性的物件。

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

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0