Type.BaseType 屬性

定義

取得目前 Type 所直接繼承的類型。

C#
public abstract Type? BaseType { get; }
C#
public abstract Type BaseType { get; }

屬性值

目前 Type 直接繼承自的 Type,如果目前 null 表示 Type 類別或介面,則為 Object

實作

範例

下列範例示範如何使用 BaseType 屬性。

C#
using System;
class TestType
{
    public static void Main()
    {
        Type t = typeof(int);
        Console.WriteLine("{0} inherits from {1}.", t,t.BaseType);
    }
}

下列範例會使用遞迴來列出元件中找到之每個類別的完整繼承階層。 此範例會定義名為 C 的類別,其衍生自名為 B 的類別,接著衍生自名為 的 A 類別。

C#
using System;

public class Example
{
   public static void Main()
   {
      foreach (var t in typeof(Example).Assembly.GetTypes()) {
         Console.WriteLine("{0} derived from: ", t.FullName);
         var derived = t;
         do { 
            derived = derived.BaseType;
            if (derived != null) 
               Console.WriteLine("   {0}", derived.FullName);
         } while (derived != null);
         Console.WriteLine(); 
      } 
   }
}

public class A {} 

public class B : A
{}

public class C : B   
{}
// The example displays the following output:
//       Example derived from:
//          System.Object
//       
//       A derived from:
//          System.Object
//       
//       B derived from:
//          A
//          System.Object
//       
//       C derived from:
//          B
//          A
//          System.Object

備註

基底類型是目前類型直接繼承的來源類型。 Object 是唯一沒有基底型別的類型,因此 null 會以 的基底型 Object 別傳回。

介面繼承自零個或多個基底介面;因此,如果 物件代表介面, Type 這個屬性會 null 傳回 。 您可以使用 或 FindInterfaces 來判斷 GetInterfaces 基底介面。

如果目前的 Type 表示建構的泛型型別,基底類型會反映泛型引數。 例如,請考慮下列宣告:

C#
class B<U> { }
class C<T> : B<T> { }

針對 Visual Basic) 中建構的類型 C<int> (C(Of Integer) ,屬性 BaseType 會傳 B<int> 回 。

如果目前 Type 代表泛型型別定義的型別參數, BaseType 則傳回類別條件約束,也就是類型參數必須繼承的類別。 如果沒有類別條件約束, BaseType 則傳 System.Object 回 。

這是唯讀的屬性。

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.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 2.0, 2.1

另請參閱