What is the difference of getting Type by using GetType() and typeof()? [duplicate]

前提是你 提交于 2019-12-29 14:17:21

问题


Possible Duplicate:
Type Checking: typeof, GetType, or is?

Which one is the preferred way to get the type?


回答1:


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.

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

  • 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

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.




回答2:


GetType() works at runtime, typeof() is a compile-time operator.

So,

// untested, schematic
void ShowType(Object x)
{
   Write(x.GetType().Name);  // depends on actual type
   // typeof(x) won't actually compile
   Write(typeof(x).Name);   // always System.Object
}

ShowType("test");

Will print System.String and System.Object.

See this question for a better example.




回答3:


GetType is a virtual method on Object - this means given an instance of a class, you can retrieve the corresponding Type object.

typeof is a C# operator - this is used to perform a compile time lookup i.e. Given a Symbol representing a Class name, retrieve the Type object for it.

if (typeof(String) == "test".GetType())



回答4:


It's not exactly the same, and the problem appears when you use inheritance.

I.e.:

WebPage1 inherits from Page, and this one inherits also from Object, so if you test for (new WebPage1()).GetType() == typeof(object) it'll return false because the types are diferent, but when you test using the is operator it's true.

((new WebPage1()) is object) is true because (new WebPage1()) is an object of type WebPage1, and also a Page and an object.

The types might be different, but is checks if you can cast safely to this type.



来源:https://stackoverflow.com/questions/4537945/what-is-the-difference-of-getting-type-by-using-gettype-and-typeof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!