转换和拆箱有什么区别?
之间有什么区别?
Expression.Convert(SomeVariableExpression, typeof(T));
在 DLR 的 LINQ 表达式中,this:和 this:
Expression.Unbox(SomeVariableExpression, typeof(T));
有关此的文档似乎有点粗略。
更重要的是,其中哪一个相当于以下 C# 代码:
(ClassA)InstanceOfClassB
Where ClassB has animplicit orexplicit Operator to cast to ClassA?
In the DLR's LINQ Expressions, what is the difference between this:
Expression.Convert(SomeVariableExpression, typeof(T));
and this:
Expression.Unbox(SomeVariableExpression, typeof(T));
The documentation on this seems a bit sketchy.
And more to the point, which one of these is equivalent to this C# code:
(ClassA)InstanceOfClassB
Where ClassB has an implicit or explicit operator to cast to ClassA?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Unbox 的重要之处在于它为您提供了装箱值的地址。 这确保您可以对未装箱的值调用方法。 如果该方法改变了值类型,那么它会改变装箱版本而不是新副本。 如果您只是执行 Convert,那么您实际上已经制作了装箱值类型的副本,然后调用它的方法会改变副本而不是原始值。
The important thing Unbox is that it gives you the address of the boxed value. This ensures that you can call a method on the unboxed value. If that method mutates the value type then it's mutating the boxed version instead of a new copy. If you merely did Convert then you'd actually have made a copy of the boxed value type and then calling a method on it would mutate the copy and not the original value.
主要区别在于 Epression.Unbox 仅用于从堆中显式拆箱值类型。
Expression.Convert
是您想要用来挂钩用户定义的转换(无论是隐式还是显式)的方法。请参阅
Expression.Convert
:并且:
Well the main difference is that
Epression.Unbox
is only needed for explicit unboxing of a value type off the heap.Expression.Convert
is the method you would want to use to hook into a user-defined conversion (whether implicit or explicit).See
Expression.Convert
:and also:
一般来说,装箱采用值类型并将其包装在对象中。 拆箱则相反。 您可以将其视为装箱获取寄存器或堆栈值并将其放在堆上,返回指向该值的指针。 拆箱将堆上的对象放入寄存器或堆栈帧中。 底层数据类型保持不变。
将更改一种数据类型转换为另一种数据类型。
In general, boxing takes a value type and wraps it in an object. Unboxing does the reverse. You can think of this as boxing takes a register or stack value and puts it on the heap, returning a pointer to that value. Unboxing takes an object on the heap and puts it into a register or stack frame. The underlying datatype stays the same.
Convert changes one datatype into another.
Expression.Convert 相当于进行强制转换。
Expression.Convert is the equivalent of doing a cast.