初始化 C++/CLI 结构数组

Initialize C++/CLI array of structures

我希望像在 C++ POD 类型中那样部分初始化结构数组。 String^ 通常是一个 char* 但托管 C++ 不允许这样。

#include "stdafx.h"

using namespace System;

ref struct Field
{
    String^ name;
    int fences;
    int length;
};

int main(array<System::String ^> ^args)
{
    array<Field^>^ farm =
    {
        { "eenie", 10 },
        { "meenie", 20 },
        { "miny", 4 }
    };

    for each (Field^ field in farm)
    {
        field->length = field->fences * 22;
    }

    return 0;
}

这导致

1>arrayinit.cpp(18): error C2440: 'initializing' : cannot convert from 'const char [6]' to 'Field ^'
1>          Reason: cannot convert from 'const char *' to 'Field ^'
1>          No user-defined-conversion operator available, or
1>          Cannot convert an unmanaged type to a managed type

所以我尝试了

#include "stdafx.h"

using namespace System;

ref struct Field
{
    String^ name;
    int fences;
    int length;
};

int main(array<System::String ^> ^args)
{
    array<Field^>^ farm =
    {
        { String("eenie"), 10 },
        { String("meenie"), 20 },
        { String("miny"), 4 }
    };

    for each (Field^ field in farm)
    {
        field->length = field->fences * 22;
    }

    return 0;
}

现在我明白了

1>arrayinit.cpp(18): error C2440: 'initializing' : cannot convert from 'System::String' to 'Field ^'
1>          No user-defined-conversion operator available, or
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>arrayinit.cpp(18): error C2078: too many initializers

我看过的几乎每个示例都只说明了如何初始化字符串或整数数组。我还没有找到初始化包含字符串的结构数组的方法。

有没有一种简单的方法可以做到这一点,还是我必须创建一个特殊的构造函数并对每个元素进行 gcnew?

我发现我可以使用特殊的构造函数 gcnew 每个元素。有没有类似于 POD 初始化的更简单的方法?

#include "stdafx.h"

using namespace System;

ref struct Field
{
    String^ name;
    int fences;
    int length;

    Field(String^ x, int in_fences)
    {
        name = x;
        fences = in_fences;
    }
};

int main(array<System::String ^> ^args)
{
    array<Field^>^ farm =
    {
        gcnew Field("eenie", 10 ),
        gcnew Field("meenie", 20 ),
        gcnew Field("miny", 4 )
    };

    for each (Field^ field in farm)
    {
        field->length = field->fences * 22;
    }

    return 0;
}

或者,如果将 Field 更改为值而不是引用,

#include "stdafx.h"

using namespace System;

value struct Field
{
    String^ name;
    int fences;
    int length;

    Field(String^ x, int in_fences)
    {
        name = x;
        fences = in_fences;
    }

    void Init()
    {
        length = fences * 22;
    }
};

int main(array<System::String ^> ^args)
{
    array<Field>^ farm =
    {
        Field("eenie", 10 ),
        Field("meenie", 20 ),
        Field("miny", 4 )
    };

    for each (Field% field in farm)
    {
        field.Init();
    }

    return 0;
}

这比 gcnewing 每个字段稍微好一点。