如何检查对象是否为某种类型 [英] How to check if an object is a certain type

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

问题描述

我将各种对象传递给子例程以运行相同的进程,但每次使用不同的对象.例如,在一种情况下,我使用的是 ListView,而在另一种情况下,我正在传递一个 DropDownList.

I am passing various objects to a subroutine to run the same process but using a different object each time. For example, in one case I am using a ListView and in another case I am passing a DropDownList.

我想检查传递的对象是否是 DropDownList,如果是,则执行一些代码.我该怎么做?

I want to check if the object being passed is a DropDownList then execute some code if it is. How do I do this?

到目前为止我的代码不起作用:

My code so far which doesn't work:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj Is System.Web.UI.WebControls.DropDownList Then

    End If
    Obj.DataBind()
End Sub

推荐答案

在 VB.NET 中,您需要使用 GetType 方法 来检索对象实例的类型,以及 GetType() 运算符 以检索另一种已知类型的类型.

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

拥有这两种类型后,您可以使用 Is 运算符简单地比较它们.

Once you have the two types, you can simply compare them using the Is operator.

所以你的代码实际上应该是这样写的:

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

您还可以使用 TypeOf 运算符 而不是 GetType 方法.请注意,这会测试您的对象是否与给定类型兼容,而不是它是同一类型.看起来像这样:

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

<小时>

完全无关紧要的吹毛求疵:传统上,在编写 .NET 代码(VB.NET 或 C#)时,参数的名称是驼峰式的(这意味着它们总是以小写字母开头).这使得它们很容易与类、类型、方法等一目了然区分.


Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

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

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