初始化一个结构体数组

发布于 2024-12-01 21:00:27 字数 666 浏览 0 评论 0原文

可能的重复:
如何初始化结构体数组?
在 C# 中初始化结构体数组

C#,Visual studio 2010

我想要声明一个结构体数组并同时初始化它,但无法正确执行 我如何写入默认初始化由结构组成的数组?

以下内容不会通过编译器,但会显示我想要存档的内容的想法

    private struct PrgStrTrans_t
    {
        public int id;
        public string name;
        public string fname;
    }

    private PrgStrTrans_t[] PrgStrTrans = { {1, "hello", "there"}, {2, "Fun", thisone"}}

是否可能?

Possible Duplicates:
How to initialize array of struct?
Initializing an Array of Structs in C#

C#, Visual studio 2010

I want declare an array of struct and initialize it on the same time but can not get it right
How do i write to default initialize an array consisting of structs ?

The following wont go through the compiler but show the idea of what I want to archive

    private struct PrgStrTrans_t
    {
        public int id;
        public string name;
        public string fname;
    }

    private PrgStrTrans_t[] PrgStrTrans = { {1, "hello", "there"}, {2, "Fun", thisone"}}

Is it possible at all ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心房敞 2024-12-08 21:00:28

将构造函数添加到结构中,并将 new PrgStrTrans(...), 放在数组的每一行上。

像这样:

private struct PrgStrTrans_t
{
    public int id;
    public string name;
    public string fname;

    public PrgStrTrans_t(int i, string n, string f)
    {
        id = i;
        name = n;
        fname = f;
    }
}

private PrgStrTrans_t[] PrgStrTrans = {
                                          new PrgStrTrans_t(4, "test", "something"),
                                          new PrgStrTrans_t(2, "abcd", "1234")
                                      }

Add a constructor to your struct, and put new PrgStrTrans(...), on each line of the array.

Like this:

private struct PrgStrTrans_t
{
    public int id;
    public string name;
    public string fname;

    public PrgStrTrans_t(int i, string n, string f)
    {
        id = i;
        name = n;
        fname = f;
    }
}

private PrgStrTrans_t[] PrgStrTrans = {
                                          new PrgStrTrans_t(4, "test", "something"),
                                          new PrgStrTrans_t(2, "abcd", "1234")
                                      }
半城柳色半声笛 2024-12-08 21:00:28
private PrgStrTrans_t[] PrgStrTrans = { new PrgStrTrans_t() { id = 1, name = "hello", fname = "there"},new PrgStrTrans_t() {id = 2, name = "Fun", fname = "thisone"}};

如果您创建一个构造函数会更好,这样可以避免键入属性名称。

private PrgStrTrans_t[] PrgStrTrans = { new PrgStrTrans_t() { id = 1, name = "hello", fname = "there"},new PrgStrTrans_t() {id = 2, name = "Fun", fname = "thisone"}};

It would be better if you made a constructor, that would avoid typing the property names.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文