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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11312111/
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-08-09 17:21:43  来源:igfitidea点击:

When and where to use GetType() or typeof()?

c#.nettypestypeofgettype

提问by Nikhil Agrawal

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 isoperator for checking type but my understanding fails when I use typeof()and GetType()

我自己使用is运算符来检查类型,但是当我使用typeof()GetType()

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

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

采纳答案by Jon Skeet

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

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

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

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

Note that unless you onlywant 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
}

回答by Jonathon Reinhart

You may find it easier to use the iskeyword:

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

if (mycontrol is TextBox)

回答by Fr33dan

typeOfis 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. GetTypeis a method of the object class that can be used on an instance.

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

回答by Olivier Jacot-Descombes

typeofis applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetTypeis called on an object at runtime. In both cases the result is an object of the type System.Typecontaining meta-information on a type.

typeof应用于编译时已知的类型或泛型类型参数的名称(作为标识符,而不是字符串)。GetType在运行时在对象上调用。在这两种情况下,结果都是一个System.Type包含类型元信息的类型的对象。

Example where compile-time and run-time types are equal

编译时和运行时类型相等的示例

string s = "hello";

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

t1 == t2 ==> true

t1 == t2 ==> true

Example where compile-time and run-time types are different

编译时和运行时类型不同的示例

object obj = "hello";

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

t1 == t2 ==> false

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable objis not the same as the runtime type of the object referenced by obj.

即变量的编译时类型(静态类型)与obj引用的对象的运行时类型不同obj



Testing types

测试类型

If, however, you only want to know whether mycontrolis a TextBoxthen you can simply test

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

if (mycontrol is TextBox)

Note that this is not completely equivalent to

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

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

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

因为mycontrol可能有一个派生自TextBox. 在这种情况下,第一个比较产生true,第二个false! 在大多数情况下,第一个更简单的变体是可以的,因为从 派生的控件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 asoperator followed by a test for nullis more performing.

测试一个值是否属于给定类型和强制转换(再次涉及相同的测试)对于长继承链来说都是耗时的。使用as运算符后跟测试 for 性能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 having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

顺便说一句:这也适用于值类型。非常方便测试和拆箱。请注意,您无法测试可空值类型:

if (o is int? ni) ===> does NOT compile!

This is because either the value is nullor it is an int. This works for int? oas well as for object o = new Nullable<int>(x);:

这是因为该值要么nullint. 这适用int? oobject o = new Nullable<int>(x);

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Valueproperty.

我喜欢它,因为它消除了访问Nullable<T>.Value属性的需要。