vb.net 如何确定类型是否在继承层次结构中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16859728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:49:09  来源:igfitidea点击:

How to determine if a type is in the inheritance hierarchy

c#vb.netinheritance

提问by XN16

I need to determine if an object has a specific type in it's inheritance hierarchy, however I can't find a good way of doing it.

我需要确定一个对象在它的继承层次结构中是否具有特定类型,但是我找不到这样做的好方法。

An very basic example version of my classes are:

我的课程的一个非常基本的示例版本是:

Public Class Domain

End Class

Public Class DerivedOne
    Inherits Domain

End Class

Public Class DerivedTwo
    Inherits DerivedOne

End Class

Public Class DerivedThree
    Inherits Domain

End Class

The following does work, however it isn't very elegant in my opinion. Also the more levels of inheritance that get created, the more checks need to be done and it would be easy to forget this piece of code needs to be updated.

以下确实有效,但在我看来它不是很优雅。此外,创建的继承级别越多,需要进行的检查就越多,很容易忘记这段代码需要更新。

If GetType(T) Is GetType(Domain) OrElse _
    GetType(T).BaseType Is GetType(Domain) OrElse _
    GetType(T).BaseType.BaseType Is GetType(Domain) Then

End If

Is there a way of getting 'Is type of Domain anywhere in T's inheritance hierarchy'?

有没有办法获得“域的类型是否在 T 的继承层次结构中的任何地方”?

(Answers welcome in C# or VB.NET)

(欢迎在 C# 或 VB.NET 中回答)



UPDATE

更新

One bit of vital information I missed out due to my own idiocy!

由于自己的愚蠢,我错过了一点重要的信息!

T is a Type object (from the class' generic type)

T 是一个 Type 对象(来自类的泛型类型)

回答by Dan Puzey

You can use the Type.IsAssignableFrommethod.

您可以使用该Type.IsAssignableFrom方法。

In VB:

在VB中:

If GetType(Domain).IsAssignableFrom(GetType(DerivedThree)) Then

In C#:

在 C# 中:

if (typeof(Domain).IsAssignableFrom(typeof(DerivedThree)))

回答by floydheld

Why is nobody mentioning Type.IsSubclassOf(Type)?

为什么没人提Type.IsSubclassOf(Type)

https://docs.microsoft.com/en-us/dotnet/api/system.type.issubclassof?view=netframework-4.7.2

https://docs.microsoft.com/en-us/dotnet/api/system.type.issubclassof?view=netframework-4.7.2

Careful, it returns false if called for two equal types ;)

小心,如果调用两个相等的类型,它会返回 false ;)

回答by Kaveh Shahbazian

In C# (VB should have this too) you can use a shorthand to perform checking and using the variable and avoiding the casting part:

在 C# 中(VB 也应该有这个),您可以使用速记来执行检查和使用变量并避免铸造部分:

var val = x as Domain;

And then use vallike this:

然后val像这样使用:

if(val != null)
{
    // use val
}

回答by tafa

How about is operator?

如何为运营商

if(obj is Domain)
{
    // 
}