RuntimeTypeHandle和Type有什么区别?
时间:2020-03-05 18:46:40 来源:igfitidea点击:
为什么在我的代码中一个又一个地使用?
解决方案
回答
Caution: This answer appears to be out of date. It was posted before .NET 4 became available, which apparently introduced some optimizations regarding Type and thus rendered the information in this answer obsolete. See this more recent answer for details.
根据Vance Morrison的这篇博客文章(2006年),RuntimeTypeHandle是一个值类型(struct),它包装了一个非托管指针,因此Type.GetTypeHandle(obj).Equals(anotherHandle)可以更快地用于与" obj.GetType()。Equals(anotherType)"进行严格的"完全相同的类型"比较,后者创建的" System.Type"实例显然更重。
但是,它也不太明显,并且肯定属于"微优化"类别,因此,如果我们想知道何时需要一个,则应该只使用System.Type。
回答
在.NET 4.0 Beta 1中,RuntimeTypeHandle仅包装RuntimeType。
看来,将其用作廉价的"类型"代理的所有好处都已荡然无存。
上述声明的证据:
- 微软对System.RuntimeTypeHandle类型的参考资料表明,这种类型确实只是围绕System.RuntimeType的包装。
- Sandro Magi在2013年的博客文章" CLR:动态类型测试的成本"中包含一个基准测试和最后一条注释,该注释和最终说明显示了RuntimeTypeHandle的预期性能优势已在.NET 4中消失。