.net 如何检查对象是否为某种类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6580044/
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
How to check if an object is a certain type
提问by Leah
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.
我将各种对象传递给子程序以运行相同的进程,但每次使用不同的对象。例如,在一种情况下,我使用的是 ListView,而在另一种情况下,我正在传递一个 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?
我想检查传递的对象是否是 DropDownList,如果是,则执行一些代码。我该怎么做呢?
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
回答by Cody Gray
In VB.NET, you need to use the GetTypemethodto retrieve the type of an instance of an object, and the GetType()operatorto retrieve the type of another known type.
在VB.NET中,需要使用GetType方法检索对象实例的类型,使用GetType()运算符检索另一种已知类型的类型。
Once you have the two types, you can simply compare them using the Isoperator.
拥有这两种类型后,您可以使用Is运算符简单地比较它们。
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
You can also use the TypeOfoperatorinstead of the GetTypemethod. Note that this tests if your object is compatiblewith the given type, not that it is the same type. That would look like this:
您也可以使用TypeOf运算符代替GetType方法。请注意,这会测试您的对象是否与给定类型兼容,而不是它是同一类型。那看起来像这样:
If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then
End If
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.
完全无关紧要的吹毛求疵:传统上,在编写 .NET 代码(VB.NET 或 C#)时,参数的名称是驼峰式的(这意味着它们总是以小写字母开头)。这使它们易于与类、类型、方法等区分开来。
回答by Ama
Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.
与 Cody Gray 的回复有关的更多细节。由于我花了一些时间来消化它,我认为它可能对其他人有用。
First, some definitions:
首先,一些定义:
- There are TypeNames, which are string representations of the type of an object, interface, etc. For example,
Baris a TypeName inPublic Class Bar, or inDim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described. - There are
System.Typeobjects which contain a value. This value indicates a type; just like aStringwould take some text or anIntwould take a number, except we are storing types instead of text or numbers.Typeobjects contain the type definitions, as well as its corresponding TypeName.
- 有 TypeNames,它们是对象、接口等类型的字符串表示形式。例如,
Bar是一个 TypeName inPublic Class Bar或 inDim Foo as Bar。TypeNames 可以被视为代码中使用的“标签”,用于告诉编译器在描述所有可用类型的字典中查找哪个类型定义。 - 有些
System.Type对象包含一个值。这个值表示一个类型;就像 aString接受一些文本或 anInt接受一个数字一样,除了我们存储的是类型而不是文本或数字。Type对象包含类型定义,以及其对应的 TypeName。
Second, the theory:
二、理论:
Foo.GetType()returns aTypeobject which contains the type for the variableFoo. In other words, it tells you whatFoois an instance of.GetType(Bar)returns aTypeobject which contains the type for the TypeNameBar.In some instances, the type an object has been
Castto is different from the type an object was first instantiated from. In the following example, MyObj is anIntegercast into anObject:Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)
Foo.GetType()返回一个Type包含变量类型的对象Foo。换句话说,它告诉您什么Foo是实例。GetType(Bar)返回一个Type包含 TypeName 类型的对象Bar。在某些情况下,对象所
Cast使用的类型与对象第一次实例化的类型不同。在以下示例中, MyObj 被Integer转换为Object:Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)
So, is MyObjof type Objector of type Integer? MyObj.GetType()will tell you it is an Integer.
那么,是MyObj类型Object还是类型Integer?MyObj.GetType()会告诉你它是一个Integer.
- But here comes the
Type Of Foo Is Barfeature, which allows you to ascertain a variableFoois compatible with a TypeNameBar.Type Of MyObj Is IntegerandType Of MyObj Is Objectwill both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks
- 但是这里有一个
Type Of Foo Is Bar功能,它允许您确定变量Foo与 TypeName 兼容Bar。Type Of MyObj Is Integer并且Type Of MyObj Is Object都将返回 True。在大多数情况下,如果变量属于 TypeName 或派生自 TypeName 的 Type,则 TypeOf 将指示该变量与 TypeName 兼容。更多信息:https: //docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks
The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.
下面的测试很好地说明了每个提到的关键字和属性的行为和用法。
Public Sub TestMethod1()
Dim MyValInt As Integer = 42
Dim MyValDble As Double = CType(MyValInt, Double)
Dim MyObj As Object = CType(MyValDble, Object)
Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
Debug.Print(MyObj.GetType.ToString) 'Returns System.Double
Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False
Debug.Print(TypeOf MyObj Is Integer) 'Returns False
Debug.Print(TypeOf MyObj Is Double) '# Returns True
Debug.Print(TypeOf MyObj Is Object) '# Returns True
End Sub
EDIT
编辑
You can also use Information.TypeName(Object)to get the TypeName of a given object. For example,
您还可以使用Information.TypeName(Object)来获取给定对象的 TypeName。例如,
Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

