One constructor for a class and its nested classes

For this example, suppose we are making a Clue β„’ style game. We have a class for each room in the mansion and subclasses for the suspect and weapons in each room. Sort of:

class Room
{
  public string Name;
  public int Width;
  public int Height;
  // and so on...

  public class Suspect
  {
    public string Name;
    public bool isPurple;
  }

  public class Weapon
  {
    public string Name;
    public bool IsMetal;
  }
}

Before adding the Suspect and Weapon classes, the room constructor looked something like this:

public Room(string Name, int Width, int Height)
{
  this.Name = Name;
  this.Width = Width;
  this.Height = Height;
}

The initialization of the room was as simple as: Room[i] = new Room("Conservatory", 7, 3);- but after entering the nested classes, can they be initialized through a common constructor with the main class? Sort of:

Room[i] = new Room("Library", 8, 5, "Professor Plum", true, "Candlestick", true);

It seems that I do not see examples of such a setting. How can i do this?

+5
source share
4 answers

Instead of having so many options for your constructor, why not do something like this?

public class Room
{
    public Room(Suspect suspect, Weapon weapon)
    {
        SuspectInRoom = suspect;
        WeaponInRoom = weapon;
    }

    public Suspect SuspectInRoom { get; set; }
    public Weapon WeaponInRoom { get; set; }
}

// Example usage:

Suspect coronelCustard = new Suspect("Coronel Custard");
Weapon musket = new Weapon("Musket");

Room someRoom = new Room(coronelCustard, musket);

// Then your room can be used to access all sorts of data.

Console.WriteLine(someRoom.SuspectInRoom.Nickname); // "The Big Kahuna"
Console.WriteLine(someRoom.WeaponInRoom.AttackDamage); // "20"

, ? ...

, .

:

Room someRoom = new Room(new Suspect("Colonel Custard"), new Weapon("Musket"));

, , . . .

+7

... :

   var room = new Room { Name = "Library",
                         Width = 7,
                         Height = 3,
                         Suspect = new Suspect { Name = "Professor Plum",
                                                 PlaysCroquet = false },
                         Weapon = new Weapon { Name = "Candlestick",
                                               IsShiny = true }
                        };
+5

Suspect Weapon, Room ( , , ).

. - - , Room ( , ).

, :

Room[i] = new Room("Library", 8, 5, new Suspect("Professor Plum", false), new Weapon("Candlestick", true));
+2

, .

, , . - int string *.

*: , - , /, .

+1

All Articles