何时何地使用GetType()或typeof()? [重复]

时间:2022-08-19 17:07:52

This question already has an answer here:

这个问题在这里已有答案:

Why this works

为什么会这样

if (mycontrol.GetType() == typeof(TextBox))
{} 

and this do not?

这不是吗?

Type tp = typeof(mycontrol);

But this works

但这很有效

Type tp = mycontrol.GetType();

I myself use is operator for checking type but my understanding fails when I use typeof() and GetType()

我自己使用的是运算符来检查类型,但是当我使用typeof()和GetType()时我的理解失败了

Where and when to use GetType() or typeof()?

何时何地使用GetType()或typeof()?

4 个解决方案

#1


69  

typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.

typeof是一个运算符,用于获取在编译时已知的类型(或至少是泛型类型参数)。 typeof的操作数始终是类型或类型参数的名称 - 永远不是具有值的表达式(例如变量)。有关更多详细信息,请参阅C#语言规范。

GetType() is a method you call on individual objects, to get the execution-time type of the object.

GetType()是您在单个对象上调用的方法,用于获取对象的执行时类型。

Note that unless you only want exactly instances of TextBox (rather than instances of subclasses) you'd usually use:

请注意,除非您只想要TextBox的实例(而不是子类的实例),否则通常会使用:

if (myControl is TextBox)
{
    // Whatever
}

Or

要么

TextBox tb = myControl as TextBox;
if (tb != null)
{
    // Use tb
}

#2


29  

typeof is applied to a name of a type or generic type parameter known at compile time. GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

typeof应用于编译时已知的类型或泛型类型参数的名称。在运行时在对象上调用GetType。在这两种情况下,结果都是System.Type类型的对象,其中包含类型的元信息。

If you have

如果你有

string s = "hello";

These two lines are valid

这两行是有效的

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2                    ==> true

But

object obj = "hello";

These two lines are valid

这两行是有效的

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2                    ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type (the dynamic type) of the object referenced by obj. (Here "dynamic" has nothing to do with the keyword dynamic!)

即,变量obj的编译时类型(静态类型)与obj引用的对象的运行时类型(动态类型)不同。 (这里“动态”与关键字动态无关!)


Testing types

测试类型

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

但是,如果您只想知道mycontrol是否是TextBox,那么您可以简单地进行测试

if (mycontrol is TextBox)

Note that this is not completely equivalent to

请注意,这并不完全等同于

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

因为mycontrol可能有一个派生自TextBox的类型。在这种情况下,第一个比较产生真,第二个假!在大多数情况下,第一个也更简单的变体是OK,因为从TextBox派生的控件继承了TextBox所具有的所有内容,可能会为它添加更多内容,因此与TextBox分配兼容。

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

铸件

If you have the following test followed by a cast and T is nullable ...

如果您有以下测试,然后是演员,T可以为空...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

...你可以把它改成......

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

测试值是否属于给定类型和强制转换(再次涉及相同的测试)对于长继承链来说都是耗时的。使用as运算符后跟null测试更有效。

Starting with C# 7.0 you can simplify the code by using pattern matching:

从C#7.0开始,您可以使用模式匹配来简化代码:

if (obj is T t) {
    // t is a variable of type T
    ...
}

#3


7  

typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.

typeOf是一个C#关键字,当您拥有该类的名称时使用该关键字。它在编译时计算,因此不能在运行时创建的实例上使用。 GetType是可以在实例上使用的对象类的方法。

#4


5  

You may find it easier to use the is keyword:

您可能会发现使用is关键字更容易:

if (mycontrol is TextBox)

#1


69  

typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.

typeof是一个运算符,用于获取在编译时已知的类型(或至少是泛型类型参数)。 typeof的操作数始终是类型或类型参数的名称 - 永远不是具有值的表达式(例如变量)。有关更多详细信息,请参阅C#语言规范。

GetType() is a method you call on individual objects, to get the execution-time type of the object.

GetType()是您在单个对象上调用的方法,用于获取对象的执行时类型。

Note that unless you only want exactly instances of TextBox (rather than instances of subclasses) you'd usually use:

请注意,除非您只想要TextBox的实例(而不是子类的实例),否则通常会使用:

if (myControl is TextBox)
{
    // Whatever
}

Or

要么

TextBox tb = myControl as TextBox;
if (tb != null)
{
    // Use tb
}

#2


29  

typeof is applied to a name of a type or generic type parameter known at compile time. GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

typeof应用于编译时已知的类型或泛型类型参数的名称。在运行时在对象上调用GetType。在这两种情况下,结果都是System.Type类型的对象,其中包含类型的元信息。

If you have

如果你有

string s = "hello";

These two lines are valid

这两行是有效的

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2                    ==> true

But

object obj = "hello";

These two lines are valid

这两行是有效的

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2                    ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type (the dynamic type) of the object referenced by obj. (Here "dynamic" has nothing to do with the keyword dynamic!)

即,变量obj的编译时类型(静态类型)与obj引用的对象的运行时类型(动态类型)不同。 (这里“动态”与关键字动态无关!)


Testing types

测试类型

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

但是,如果您只想知道mycontrol是否是TextBox,那么您可以简单地进行测试

if (mycontrol is TextBox)

Note that this is not completely equivalent to

请注意,这并不完全等同于

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

因为mycontrol可能有一个派生自TextBox的类型。在这种情况下,第一个比较产生真,第二个假!在大多数情况下,第一个也更简单的变体是OK,因为从TextBox派生的控件继承了TextBox所具有的所有内容,可能会为它添加更多内容,因此与TextBox分配兼容。

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

铸件

If you have the following test followed by a cast and T is nullable ...

如果您有以下测试,然后是演员,T可以为空...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

...你可以把它改成......

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

测试值是否属于给定类型和强制转换(再次涉及相同的测试)对于长继承链来说都是耗时的。使用as运算符后跟null测试更有效。

Starting with C# 7.0 you can simplify the code by using pattern matching:

从C#7.0开始,您可以使用模式匹配来简化代码:

if (obj is T t) {
    // t is a variable of type T
    ...
}

#3


7  

typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.

typeOf是一个C#关键字,当您拥有该类的名称时使用该关键字。它在编译时计算,因此不能在运行时创建的实例上使用。 GetType是可以在实例上使用的对象类的方法。

#4


5  

You may find it easier to use the is keyword:

您可能会发现使用is关键字更容易:

if (mycontrol is TextBox)