获取类型使用的GetType()和typeof运算()的区别是什么?区别、类型、GetType、typeof

2023-09-03 00:30:45 作者:unnecessary(多余)

可能重复:   类型检查:?typeof运算,的GetType,或者是

哪一个是preferred的方式来获得的类型?

Which one is the preferred way to get the type?

推荐答案

您只能使用 typeof运算()时,你知道该类型在编译时,而你试图获得相应的键入对象。 (虽然类型可以是一个泛型类型参数,例如:的typeof(T) A类的类型参数中的 T 。)有没有需要是该类型的可使用的typeof 的任何实例。操作数为的typeof 始终是一个类型或类型参数的名称的。它不能是一个变量或类似的东西。

You can only use typeof() when you know that type at compile time, and you're trying to obtain the corresponding Type object. (Although the type could be a generic type parameter, e.g. typeof(T) within a class with a type parameter T.) There don't need to be any instances of that type available to use typeof. The operand for typeof is always the name of a type or type parameter. It can't be a variable or anything like that.

现在比较,与 object.GetType()。这将让这就是所谓的对象的实际类型。这意味着:

Now compare that with object.GetType(). That will get the actual type of the object it's called on. This means:

您不需要知道在编译时的类型(通常不这样做) 您的执行的需求就会成为类型的实例(否则你有什么可称之为的GetType 上) 实际的类型并不需要访问到code - 例如,它可以是一个内部类型在不同的装配 You don't need to know the type at compile time (and usually you don't) You do need there to be an instance of the type (as otherwise you have nothing to call GetType on) The actual type doesn't need to be accessible to your code - for example, it could be an internal type in a different assembly

一个奇怪的问题:的GetType 会给由于拳击的工作方式意想不到的答案,对空值类型。调用到的GetType 总会涉及拳击的任意的值类型,包括可空类型和空值类型的装​​箱值可以是一个空引用或引用一个非空值类型的实例。

One odd point: GetType will give unexpected answers on nullable value types due to the way that boxing works. A call to GetType will always involve boxing any value type, including a nullable value type, and the boxed value of a nullable value type is either a null reference or a reference to an instance of a non-nullable value type.