Type.IsInstanceOfType(Object) 方法

定義

判斷指定的物件是否為目前 Type 的執行個體。

C#
public virtual bool IsInstanceOfType(object? o);
C#
public virtual bool IsInstanceOfType(object o);

參數

o
Object

要與目前的類型比較的物件。

傳回

如果在目前 Type 位於 o 所代表之物件的階層架構中,或者目前 Type 位於 o 支援的介面中,則為 true。 如果都不是這些情況,或者如果 onull,又或者如果目前 Type 為開放式泛型類型 (亦即 ContainsGenericParameters 會傳回 true),則為 false

實作

範例

下列範例示範 IsInstanceOfType 方法的用法。

C#
using System;

public interface IExample {}

public class BaseClass : IExample {}

public class DerivedClass : BaseClass {}

public class Example
{
    public static void Main()
    {
        var interfaceType = typeof(IExample);
        var base1 = new BaseClass();
        var base1Type = base1.GetType();
        var derived1 = new DerivedClass();
        var derived1Type = derived1.GetType();
        int[] arr = new int[11];

        Console.WriteLine("Is int[] an instance of the Array class? {0}.",
                           typeof(Array).IsInstanceOfType(arr));
        Console.WriteLine("Is base1 an instance of BaseClass? {0}.",
                          base1Type.IsInstanceOfType(base1));
        Console.WriteLine("Is derived1 an instance of BaseClass? {0}.",
                          base1Type.IsInstanceOfType(derived1));
        Console.WriteLine("Is base1 an instance of IExample? {0}.",
                          interfaceType.IsInstanceOfType(base1));
        Console.WriteLine("Is derived1 an instance of IExample? {0}.",
                          interfaceType.IsInstanceOfType(derived1));
    }
}
// The example displays the following output:
//    Is int[] an instance of the Array class? True.
//    Is base1 an instance of BaseClass? True.
//    Is derived1 an instance of BaseClass? True.
//    Is base1 an instance of IExample? True.
//    Is derived1 an instance of IExample? True.

備註

這個方法可由衍生類別覆寫。

備註

建構的類型不是其泛型型別定義的實例。 也就是說, MyGenericList<int> Visual Basic) 中的 (MyGenericList(Of Integer) 不是 Visual Basic) 中 (MyGenericList(Of T) 的實例 MyGenericList<T>

適用於

產品 版本
.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