Difference between array<T> and array<T^> where T is ValueType

与世无争的帅哥 提交于 2019-12-20 05:16:07

问题


I'm writing a C++/CLI wrapper over native lib for my C# project. I'm trying to convert std::vector<unsigned char> in native c++ to System.Byte[] in C#. In C++/CLI both variants are valid

auto arr = gcnew array<System::Byte>(10);
auto arr = gcnew array<System::Byte^>(10);

But in first case in C# code we got System::Byte[] type whereas in second case we got System::ValueType[].

So my question is why we got such strange behavior?


回答1:


The ^ hat should only be used on reference types. Byte is a value type so array<System::Byte> is the proper declaration.

Unfortunately C++/CLI also permits an array of Byte^, turning a value into an object is a supported scenario in .NET code. The array now contains references to objects, the object is the boxed value of the byte. Boxing conversions implement the famous illusion that value types inherit from System::ValueType which derives from System::Object. Instead of 1 byte of storage for an element, you now need 4 bytes for the object reference and 12 bytes for the boxed byte object in 32-mode.

Well, don't do that. I've never yet encountered a scenario where this was necessary or useful. There are a few scenarios where boxing is necessary, Reflection for example, but it then makes more sense to go directly to Object^ since that's the way such methods are documented.



来源:https://stackoverflow.com/questions/39294682/difference-between-arrayt-and-arrayt-where-t-is-valuetype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!