tailieunhanh - Expert C++/CLI .NET for Visual C++ Programmers phần 2

Các công cụ đơn giản nhất có sẵn để sử dụng trong Animating một đối tượng là OnTime () của đối tượng ứng dụng, tuy nhiên, tối thiểu khoảng thời gian một giây của nó (xem Chương 4) sẽ ngăn chặn Excetris đạt đến một mức độ cao của khó khăn cho người chơi. | 22 CHAPTER 2 MANAGED TYPES INSTANCES AND MEMORY int main DateTime for int f dt dt DateTime Now i 0 i 1000000 i Every iteration of the for loop calls f passing the dt value. Since f expects an argument of type DateTimeA a tracking handle to DateTime the dt value is boxed. This can be a significant overhead for the memory allocations as well as for the GC. To avoid this overhead the object can be boxed before the loop starts DateTimeA dt DateTime Now for int i 0 i 1000000 i f dt However this approach can have side effects. If the f is implemented so that it calls a function on its argument that modifies the state of the boxed value the same object will be modified by all iterations. If a value is passed instead of a boxed object every iteration will create a new boxed object. This new boxed object will be modified and the value passed to the function will remain unchanged. To avoid these problems System DateTime does not have functions that modify the state of an object. Functions like DateTime AddDays return a new value with the modified state instead of returning an existing one. Many other value types from the FCL and other libraries however do have functions that can be used to modify the value. It is important to understand that a boxed object and the value used to create it are independent instances. Unboxing To retrieve the value from the boxed object an operation called unboxing is performed. The most obvious example of an unboxing operation is dereferencing a tracking handle to a boxed object void f VA boxedV V v boxedV unboxing and assignment of unboxed value . If the tracking handle is not of type VA a cast instead of a dereferencing operation is necessary. In this case unboxing takes place too void f ObjectA o int i int o unboxing and assignment of unboxed value . It is important to differentiate between a normal cast and an assignment of an unboxed value. Unboxing is a typed operation to unbox an object it is necessary to know the type of CHAPTER 2 .