阵列T之间的差异为T.和数组< T ^>其中T是ValueType [英] Difference between array<T> and array<T^> where T is ValueType

查看:114
本文介绍了阵列T之间的差异为T.和数组< T ^>其中T是ValueType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的C#项目在本机lib上编写C ++/CLI包装器.我正在尝试将本机c ++中的std :: vector< unsigned char>转换为C#中的System.Byte []. 在C ++/CLI中,两个变体都有效

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);

但是在第一种情况下,在C#代码中,我们得到了System :: Byte []类型,而在第二种情况下,我们得到了System :: ValueType [].

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?

推荐答案

^帽子仅可用于引用类型.字节是一种值类型,因此array<System::Byte>是正确的声明.

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

不幸的是,C ++/CLI 允许使用Byte^数组,.NET代码支持将值转换为对象.数组现在包含对对象的引用,该对象是字节的 boxed 值.装箱转换实现了一种著名的错觉,即值类型继承自System :: ValueType,而System :: ValueType继承自System :: Object.现在,在32位模式下,您需要4字节的对象引用和12字节的盒装字节对象,而不是元素的1字节存储空间.

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.

好吧,不要那样做.我从未遇到过这种情况是必要或有用的情况.在某些情况下需要装箱,例如Reflection,但是直接进入Object ^更为有意义,因为这是记录这种方法的方式.

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.

这篇关于阵列T之间的差异为T.和数组&lt; T ^&gt;其中T是ValueType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆