Type.IsSubclassOf(Type) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
public:
virtual bool IsSubclassOf(Type ^ c);
public virtual bool IsSubclassOf(Type c);
[System.Runtime.InteropServices.ComVisible(true)]
public virtual bool IsSubclassOf(Type c);
abstract member IsSubclassOf : Type -> bool
override this.IsSubclassOf : Type -> bool
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member IsSubclassOf : Type -> bool
override this.IsSubclassOf : Type -> bool
Public Overridable Function IsSubclassOf (c As Type) As Boolean
Параметры
- c
- Type
Тип для сравнения с текущим типом.
Возвращаемое значение
false значение, если c и текущий Type равный.
Реализации
- Атрибуты
Исключения
c равно null.
Примеры
В следующем примере создается класс с именем Class1DerivedC1и производным классом. Он вызывает IsSubclassOf метод для отображения, что DerivedC1 является подклассом Class1.
using System;
public class Class1 { }
public class DerivedC1 : Class1 { }
class IsSubclassTest
{
public static void Main()
{
Console.WriteLine("DerivedC1 subclass of Class1: {0}",
typeof(DerivedC1).IsSubclassOf(typeof(Class1)));
}
}
// The example displays the following output:
// DerivedC1 subclass of Class1: True
type Class1() = class end
type DerivedC1() = inherit Class1()
printfn $"DerivedC1 subclass of Class1: {typeof<DerivedC1>.IsSubclassOf typeof<Class1>}"
// The example displays the following output:
// DerivedC1 subclass of Class1: True
Public Class Class1
End Class
Public Class DerivedC1 : Inherits Class1
End Class
Public Module Example
Public Sub Main()
Console.WriteLine("DerivedC1 subclass of Class1: {0}",
GetType(DerivedC1).IsSubClassOf(GetType(Class1)))
End Sub
End Module
' The example displays the following output:
' DerivedC1 subclass of Class1: True
Комментарии
Чтобы определить любой из следующих способов, IsSubclassOf можно вызвать метод:
Является ли один класс производным от другого.
Является ли тип производным от ValueType. IsValueType Однако более эффективный способ определить, является ли тип типом значения.
Является ли тип производным от Enum. Однако метод является более эффективным способом определить, IsEnum является ли тип перечислением.
Является ли тип делегатом, то есть является ли он производным от одного Delegate или MulticastDelegate.
Метод IsSubclassOf нельзя использовать для определения того, является ли интерфейс производным от другого интерфейса или класс реализует интерфейс. IsAssignableFrom Используйте метод для этой цели, как показано в следующем примере.
using System;
public interface IInterface
{
void Display();
}
public class Implementation : IInterface
{
public void Display()
{
Console.WriteLine("The implementation...");
}
}
public class Example
{
public static void Main()
{
Console.WriteLine("Implementation is a subclass of IInterface: {0}",
typeof(Implementation).IsSubclassOf(typeof(IInterface)));
Console.WriteLine("IInterface is assignable from Implementation: {0}",
typeof(IInterface).IsAssignableFrom(typeof(Implementation)));
}
}
// The example displays the following output:
// Implementation is a subclass of IInterface: False
// IInterface is assignable from Implementation: True
type IInterface =
abstract Display : unit -> unit
type Implementation() =
interface IInterface with
member _.Display() = printfn "The implementation..."
printfn $"Implementation is a subclass of IInterface: {typeof<Implementation>.IsSubclassOf typeof<IInterface>}"
printfn $"IInterface is assignable from Implementation: {typeof<IInterface>.IsAssignableFrom typeof<Implementation>}"
// The example displays the following output:
// Implementation is a subclass of IInterface: False
// IInterface is assignable from Implementation: True
Public Interface IInterface
Sub Display()
End Interface
Public Class Implementation : Implements IInterface
Public Sub Display() _
Implements IInterface.Display
Console.WriteLine("The implementation...")
End Sub
End Class
Module Example
Public Sub Main()
Console.WriteLine("Implementation is a subclass of IInterface: {0}",
GetType(Implementation).IsSubclassOf(GetType(IInterface)))
Console.WriteLine("IInterface is assignable from Implementation: {0}",
GetType(IInterface).IsAssignableFrom(GetType(Implementation)))
End Sub
End Module
' The example displays the following output:
' Implementation is a subclass of IInterface: False
' IInterface is assignable from Implementation: True
Если текущий Type представляет параметр типа в определении универсального типа или универсального метода, он является производным от ограничения класса или от System.Object того, имеет ли он ограничение класса.
Note
За исключением случаев, когда используется с интерфейсами, IsSubclassOf это наоборот IsAssignableFrom. То есть, если t1.IsSubclassOf(t2) есть true, то t2.IsAssignableFrom(t1) это также true.
Этот метод можно переопределить производным классом.