简体   繁体   中英

Creating a List of a class within the same class?

I'm practicing C# and have only been learning for about a month. I have a question that maybe is a bit on the beginner side so I hope someone doesn't mind answering for me.

I have a class called yourCharacter. In this class sits all the information for someone's character. I want to give the user the ability to create a new character so I've created a method/function to do so. My question is, can I place a function within yourCharacter that creates a List of yourCharacter. Is this doable? Is it bad form to do it this way? Should I be creating this list in my Main class and then calling a function within the main class to do this?

I hope my question is clear enough, please let me know if you need further detail. The only reason I want to do this is because in my head it makes more sense to group my methods/functions with the class it is manipulating and or working with.

class yourCharacter{

     //insert a bunch of variables here


     public static void newChar(){

          List newCharacter = new List<yourCharacter>();

     }
}

What you have there is doable for sure.

A class can contain itself as a member. This might make sense in some scenario, but think about yours and see whether it applies. In your case it seems as if you're trying to have a mechanism to group characters - but it's not a good way to do it. Why? Read on...

Say you had a box. This box contained another box inside... that box could contain another box inside... So in that case, if I made a class which represents this kind of box it might make sense to add that class into itself. Making a class like that represents a system in reality where a box contains other boxes.

What system are you trying to abstract, so that it is useful that a character contains other characters? I can think of something: let's imagine a character in your game can swallow other characters and they'll live inside his tummy...

If you want to group them - you'd likely want to use another class which represents the system under which your characters are grouped like this: Say your game has an adventure party! The adventure party can invite other people to join and they go questing together. Let's say this adventure party has a leader which decides who can join and who can't. You still probably wouldn't make a character which contains other characters... you would rather create a class called "AdventureGroup" with a list of "ordinary" party members and a leader, you would assign a string which represents the "group nickname", and all other kinds of things which represent the group as an entity. Something like that... you get the jist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM