博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
typeof和GetType的区别
阅读量:4569 次
发布时间:2019-06-08

本文共 1334 字,大约阅读时间需要 4 分钟。

http://stackoverflow.com/questions/4537945/what-is-the-difference-of-getting-type-by-using-gettype-and-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.

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.

转载于:https://www.cnblogs.com/chucklu/p/4533389.html

你可能感兴趣的文章
Python 序列化之json、pickle
查看>>
python3 多线程笔记
查看>>
无尽的控件-GridView复合表头
查看>>
Luogu4726 【模板】多项式指数函数(NTT+多项式求逆)
查看>>
e3mall商城的归纳总结2之认识dubbo、zookeeper
查看>>
hdu 4507 吉哥系列故事——恨7不成妻
查看>>
表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列
查看>>
锡瓦塔内霍 墨西哥 / 巴克斯顿 /
查看>>
Direct3D 索引缓存
查看>>
Eclipse开发环境的配置
查看>>
Java集合框架的学习
查看>>
P4783 【模板】矩阵求逆
查看>>
centos7 离线源码安装 postgresql-9.6.6
查看>>
浅谈软件测试
查看>>
C# winform端 通过HttpWebRequest进行post和get请求,数据格式为json,后台java端接收,其中有关传输特殊字符(\t,\r,',\n,n)等处理...
查看>>
4069: [Apio2015]巴厘岛的雕塑
查看>>
yii2常用路径获取
查看>>
18 | 眼前一亮:带你玩转GUI自动化的测试报告
查看>>
Gitlab修改默认端口
查看>>
功能规格说明书
查看>>