You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向父类中的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 Card class is nested inside Deck, and you've put the Main method (the program's entry point) inside Card—this isn't standard for C# console apps, and it blocks you from accessing the DeckList array properly.
  • Private field access: DeckList is a private field of Deck, so the nested Card class 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 an Add() method (the closest equivalent to JS's push()).
  • Naming conflict: You have an enum named value and a variable named value in 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

  1. Enum renaming: value becomes CardRank to eliminate naming conflicts with variables.
  2. List instead of array: List<string> replaces the fixed-size array. The Add() method works exactly like JS's push()—no need to track an index for assignments.
  3. Cleaner class structure: The Main method lives in a separate Program class (standard for C# console apps), and deck-building logic is encapsulated in the Deck constructor.
  4. Encapsulation: The GetDeck() method exposes the private _deckList safely, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:25:09