结构中的结构
本文关键字:结构 | 更新日期: 2023-09-27 18:00:06
好吧,我正试图在另一个结构中创建一个结构,但遇到了问题。。。
代码:
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);
我得到的信息是:结构中不能有实例字段初始值设定项
行中:
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;
}
}
}
将内部结构更改为class,您就可以了。