检查实例是否为类型 [英] Check if instance is of a type

查看:52
本文介绍了检查实例是否为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用它来检查 c 是否是 TForm 的实例。

Using this to check if c is an instance of TForm.

c.GetType().Name.CompareTo("TForm") == 0

除了使用 string 作为参数外,还有其他更安全的方法吗?到 CompareTo()

Is there a more type safe way to do it besides using a string as a param to CompareTo()?

推荐答案

此处的不同答案有两个不同的含义。

The different answers here have two different meanings.

如果您要检查实例的类型是否为 ,然后

If you want to check whether an instance is of an exact type then

if (c.GetType() == typeof(TForm))

是要走的路。

如果您想知道 c TForm 的实例还是子类,然后使用 is / as

If you want to know whether c is an instance of TForm or a subclass then use is/as:

if (c is TForm)

TForm form = c as TForm;
if (form != null)

在您的脑海中应该清楚这些实际上是您想要的行为。

It's worth being clear in your mind about which of these behaviour you actually want.

这篇关于检查实例是否为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆