Type.BaseType Свойство
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Получает тип, от которого текущий Type напрямую наследует.
public:
abstract property Type ^ BaseType { Type ^ get(); };
public abstract Type? BaseType { get; }
public abstract Type BaseType { get; }
member this.BaseType : Type
Public MustOverride ReadOnly Property BaseType As Type
Значение свойства
От Type которого текущий Type объект непосредственно наследуетсяObject, или null если текущий Type представляет класс или интерфейс.
Реализации
Примеры
В следующем примере показано использование BaseType свойства.
using System;
class TestType
{
public static void Main()
{
Type t = typeof(int);
Console.WriteLine("{0} inherits from {1}.", t,t.BaseType);
}
}
let t = typeof<int>
printfn $"{t} inherits from {t.BaseType}."
Class TestType
Public Shared Sub Main()
Dim t As Type = GetType(Integer)
Console.WriteLine("{0} inherits from {1}.", t, t.BaseType)
End Sub
End Class
В следующем примере используется рекурсия для перечисления полной иерархии наследования каждого класса, найденного в сборке. В примере определяется класс с C именем, производным от класса с именем, который, в свою очередь, является производным от класса с именемBA.
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
type A() = class end
type B() = inherit A()
type C() = inherit B()
module Example =
[<EntryPoint>]
let main _ =
for t in typeof<A>.Assembly.GetTypes() do
printfn $"{t.FullName} derived from: "
let mutable derived = t
while derived <> null do
derived <- derived.BaseType
if derived <> null then
printfn $" {derived.FullName}"
printfn ""
0
// 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
Public Class Example
Public Shared Sub Main()
For Each t In GetType(Example).Assembly.GetTypes()
Console.WriteLine("{0} derived from: ", t.FullName)
Dim derived As Type = t
Do
derived = derived.BaseType
If derived IsNot Nothing Then
Console.WriteLine(" {0}", derived.FullName)
End If
Loop While derived IsNot Nothing
Console.WriteLine()
Next
End Sub
End Class
Public Class A
End Class
Public Class B : Inherits A
End Class
Public Class C : Inherits B
End Class
' 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.
Интерфейсы наследуются от нуля или более базовых интерфейсов; Поэтому это свойство возвращается null , если Type объект представляет интерфейс. Базовые интерфейсы можно определить с GetInterfaces помощью или FindInterfaces.
Если текущий Type представляет созданный универсальный тип, базовый тип отражает универсальные аргументы. В качестве примера рассмотрим следующие объявления:
class B<U> { }
class C<T> : B<T> { }
type B<'U>() = class end
type C<'T>() = inherit B<'T>()
Class B(Of U)
End Class
Class C(Of T)
Inherits B(Of T)
End Class
Для созданного типа C<int> (C(Of Integer) в Visual Basic) BaseType свойство возвращается B<int>.
Если текущий Type представляет параметр типа определения универсального типа, BaseType возвращает ограничение класса, то есть класс, который должен наследовать параметр типа. Если ограничения класса отсутствуют, BaseType возвращается System.Object.
Это свойство доступно только для чтения.