This question already has answers here:
C# compiler error: “cannot have instance field initializers in structs”
                                
                                    (7个答案)
                                
                        
                                5年前关闭。
            
                    
好,
我正在尝试在另一个内部创建结构,但是遇到了麻烦...

代码:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WAMServer
{
    class PStruct
    {
        public static PStruct.Player[] player = new PStruct.Player[100];
        public struct Player
        {
            public int ID;
            public string Username;
            public string Password;
            public PStruct.Character[] character = new PStruct.Character[2];
        }

        public struct Character
        {
            public string CharacterName;
            public string Gender;
            public string ClassId;
            public string Level;
            public sbyte MapId;
            public int X;
            public int Y;
        }
    }
}


使用结构:

PStruct.player[index].character[Convert.ToInt32(ID)].CharacterName = br.ReadString();
PStruct.player[index].character[Convert.ToInt32(ID)].Gender = br.ReadString();
PStruct.player[index].character[Convert.ToInt32(ID)].ClassId = br.ReadString();
PStruct.player[index].character[Convert.ToInt32(ID)].Level = br.ReadString();


和:

string charName = (PStruct.player[clientId].character[Convert.ToInt32(charId)].CharacterName);

string charGender = (PStruct.player[clientId].character[Convert.ToInt32(charId)].Gender);

string charClass = (PStruct.player[clientId].character[Convert.ToInt32(charId)].ClassId);

string charLevel = (PStruct.player[clientId].character[Convert.ToInt32(charId)].Level);


我收到的消息是:
struct中不能有实例字段初始化器

在该行中:

public PStruct.Character[] character = new PStruct.Character[2];


有人可以帮助我吗?

最佳答案

您不能在结构中执行此操作。

public PStruct.Character[] character = new PStruct.Character[2]; //doesn't work


new PStruct.Character[2];是编译器遇到的问题。也就是说,您正在内联初始化字段。初始化结构中字段的唯一方法是通过带有参数的显式构造函数,因为您也不能在结构中具有显式的无参数构造函数。

public struct Player
{
    public Player() { } // doesn't work either - constructor must have parameters
}


为了完成您想要的并将其保留为结构(并且在实例化该结构时不必传递虚拟参数),解决方法是使用具有显式getter和setter的良好老式属性:

public struct Player
{
    public int ID;
    public string Username;
    public string Password;

    private PStruct.Character[] character;
    public PStruct.Character[] Character
    {
        get
        {
            if (null == character)
                character = new PStruct.Character[2]; // works

            return character;
        }
        set
        {
            character = value;
        }
    }
}

09-06 02:43