那么, 我试图在另一个内部创建一个结构,但我遇到了麻烦...
代码:
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;
}
}
}
使用struct:
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];
任何人都可以帮助我?
答案 0 :(得分:1)
您不能在结构中执行此操作。
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;
}
}
}
答案 1 :(得分:0)
将你的内心结构改为上课,你就没事了。