为什么在密封的ref类中属性不能是公共的

Why can properties not be public inside a ref class sealed

本文关键字:不能 属性 密封 ref 为什么      更新时间:2023-10-16

以下代码是非法的(Visual Studio 2012 Windows Phone(创建Windows Phone direct3d应用程序))

a non-value type cannot have any public data members 'posX'

标题

ref class Placement sealed
{
public:
    Placement(
        float rotX, 
        float rotY, 
        float rotZ, 
        float posX, 
        float posY, 
        float posZ
    );
    float rotX, rotY, rotZ, posX, posY, posZ;
};

Cpp

Placement::Placement(
        float rotX, 
        float rotY, 
        float rotZ, 
        float posX, 
        float posY, 
        float posZ
    )
    :   posX( posX ),
        posY( posY ),
        posZ( posZ )
{
    this->rotX = static_cast<float>(rotX);
    this->rotY = static_cast<float>(rotY);
    this->rotZ = static_cast<float>(rotZ);
}

为什么以及如何设置属性?我习惯了普通的C++而不是C++CX(我想它是这么叫的吧?)。。。我必须创建为属性服务的方法吗

*这个问题源于我最初试图创建一个普通类并创建一个指向它的指针,但却被抱怨我不能使用*,而是必须使用^,这意味着我必须创建一个ref类。。。我真的不明白为什么?*

这与WinRT或更具体地说与ARM处理器有关吗

Is是COM中的一个限制,COM是WinRT和C++/CX语言扩展的基础。COM只允许在接口声明中使用纯虚拟方法。一个属性很好,它被模拟为getter和setter方法。不是田地。

这种限制不是人为的,它强烈地去除了实现细节。当您需要支持任意语言并让它们相互对话或与API对话时,这一点非常重要。字段有一个非常糟糕的实现细节,其位置非常依赖于实现。对齐和结构打包规则对于确定该位置非常重要,并且不能保证在语言运行时之间兼容。

使用属性是一个简单的解决方法。

这是特定于WinRT和C++/CX扩展的东西。C++/CX不允许ref类包含公共字段。您需要将公共字段替换为公共属性。

 ref class Placement sealed
{
public:
    Placement(
        float rotX, 
        float rotY, 
        float rotZ, 
        float posX, 
        float posY, 
        float posZ
    );
    property float rotX;
    property float rotY;
    property float rotZ;
    property float posX;
    property float posY;
    property float posZ;
};

属性具有由编译器自动为其生成的getter和setter函数。