如何向父类中的C#数组添加元素?
Hey there! Coming from JavaScript, it makes total sense that you'd miss the convenience of push() when working with collections in C#. Let's walk through fixing your code step by step, and I'll point out the key differences between JS and C# here.
Key Issues in Your Current Code
First, let's break down what's getting in your way:
- Nested class structure: Your
Cardclass is nested insideDeck, and you've put theMainmethod (the program's entry point) insideCard—this isn't standard for C# console apps, and it blocks you from accessing theDeckListarray properly. - Private field access:
DeckListis a private field ofDeck, so the nestedCardclass can't access it directly (C# has stricter scoping rules than JS here). - Array limitations: C# arrays have a fixed size once initialized—you can't "push" to them like JS arrays. You either need to track an index to assign values, or use a
List<string>which has anAdd()method (the closest equivalent to JS'spush()). - Naming conflict: You have an enum named
valueand a variable namedvaluein your loop—this will cause compiler errors because the names clash.
Fixed Code Example
Let's rewrite your code to fix these issues and follow C# best practices:
using System; using System.Collections.Generic; namespace ConsoleApp2 { // Rename enum to avoid variable name conflict public enum Suit { Clubs, Diamonds, Hearts, Spades } public enum CardRank { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } // Deck class manages the card collection class Deck { // Use List<string> for easy "push" (Add()) functionality private List<string> _deckList = new List<string>(); // Constructor: builds the deck when a Deck instance is created public Deck() { foreach (Suit suit in Enum.GetValues(typeof(Suit))) { foreach (CardRank rank in Enum.GetValues(typeof(CardRank))) { // String interpolation (similar to JS template literals) string descriptiveText = $"{rank} of {suit}"; // Add to the list (equivalent to JS push()) _deckList.Add(descriptiveText); } } } // Method to expose the deck (follows encapsulation principles) public List<string> GetDeck() { return _deckList; } } // Program class with the required entry point class Program { static void Main(string[] args) { // Create a new deck (constructor builds all cards automatically) Deck myDeck = new Deck(); List<string> deckCards = myDeck.GetDeck(); // Print every card in the deck foreach (string card in deckCards) { Console.WriteLine(card); } Console.ReadKey(); } } }
Key Changes Explained
- Enum renaming:
valuebecomesCardRankto eliminate naming conflicts with variables. - List instead of array:
List<string>replaces the fixed-size array. TheAdd()method works exactly like JS'spush()—no need to track an index for assignments. - Cleaner class structure: The
Mainmethod lives in a separateProgramclass (standard for C# console apps), and deck-building logic is encapsulated in theDeckconstructor. - Encapsulation: The
GetDeck()method exposes the private_deckListsafely, following C#'s best practices for field access.
If You Want to Use an Array Instead
If you specifically need a fixed-size array, here's how to adjust the Deck class:
class Deck { private string[] _deckList = new string[52]; public Deck() { int index = 0; // Track the current position in the array foreach (Suit suit in Enum.GetValues(typeof(Suit))) { foreach (CardRank rank in Enum.GetValues(typeof(CardRank))) { string descriptiveText = $"{rank} of {suit}"; _deckList[index] = descriptiveText; index++; // Move to the next array position } } } public string[] GetDeck() { return _deckList; } }
Extra C# Tips for JS Developers
- Field names in C# typically use camelCase with an underscore prefix (like
_deckList) to distinguish them from local variables. - String interpolation (
$"{rank} of {suit}") is a cleaner alternative to string concatenation, just like JS template literals. Enum.GetValues()returns the actual enum values (not just strings), giving you type safety while still allowing easy conversion to strings.
内容的提问来源于stack exchange,提问作者Simon Dean
相关产品推荐
相关产品推荐

