如何判断类型是否需要装箱?
MSDN 文档说只有值类型需要装箱,但这不适用于字符串,字符串是值类型,不需要装箱。我最初尝试了 Type.IsValueType,但由于它对字符串返回 true,所以我无法使用它来确定类型是否确实需要装箱。您还知道其他方法吗?字符串是唯一的例外吗?
更新:我在代码中犯了一个错误,我引用了一个 int 并认为它是一个字符串。字符串实际上是一种值类型,感谢您指出!
MSDN docs say that only value types need boxing, but this does not apply to string, which is a value type and does not need to be boxed. I initially tried Type.IsValueType, but since that returns true for string, I can't use it to determine whether a type really needs to be boxed. Are there any other methods you are aware of? Is string the only exception?
UPDATE: I made a mistake in my code where I referenced an int and I thought it was a string. String is in fact a value type, thanks for pointing it out guys!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的前提是不正确的。字符串实际上是一种引用类型,在许多情况下它恰好充当值类型。 Type.IsValueType 是确定值是否需要装箱的最可靠方法。
不过,如果您使用可为空的值,我会小心。
Your premise is incorrect. String is actually a reference type which just happens to act like a value type in many scenarios. Type.IsValueType is the most reliable way of determining if a value would need to be boxed or not.
I'd be careful if you work with nullable values though.
您正在编写原始 IL 吗?这是你必须关心拳击的唯一情况。
Are you writing raw IL? That's the only case in which you'll have to concern yourself with boxing.