c# - Struct in Struct -
this question has answer here:
well, i'm trying create struct inside another, , having trouble ...
the code:
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; } } }
uses 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();
and:
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);
the message is: cannot have instance field initializers in struct
in line:
public pstruct.character[] character = new pstruct.character[2];
anyone can me?
you cannot inside struct.
public pstruct.character[] character = new pstruct.character[2]; //doesn't work
the new pstruct.character[2];
compiler has problem with. is, you're initializing field inline. way initialize field in struct via explicit constructor takes parameters, cannot have explicit parameterless constructor in struct, either.
public struct player { public player() { } // doesn't work either - constructor must have parameters }
to accomplish want , keep struct (and not have pass dummy parameter when instantiating struct), workaround use old-fashioned property explicit getter , setter:
public struct player { public int id; public string username; public string password; private pstruct.character[] character; public pstruct.character[] character { { if (null == character) character = new pstruct.character[2]; // works return character; } set { character = value; } } }
Comments
Post a Comment