-2

我在 main 中调用类函数时遇到了麻烦,因为它需要同时返回 2 个列表。该函数将一张卡片从一个列表添加到另一个列表,然后将其从原始列表中删除。但是当我尝试调用该函数时,我得到了这个错误......没有重载方法“Hit”需要1个参数

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace BlackJackGameX
    {
        public class MainClass
        {
            public static void Main (string[] args)
            {

                Deck Cards = new Deck();

                Hand PlayerHand = new Hand ();

                Console.WriteLine("Welcome to Black Jack\n\nPress Enter To Start");
                Console.ReadLine ();

                PlayerHand.Hit(PlayerHand);
                PlayerHand.Hit(PlayerHand);
                PlayerHand.HandPrint();


            }
        }
    }

问题出在这个手类的 Hit Function 的底部

using System;
using System.Collections.Generic;
using System.Text;

namespace BlackJackGameX
{
    public class Hand
    {

        Deck CardDeck = new Deck ();

        public List<Card> PlayerHand;

        public Hand ()
        {

        }

        public void HandPrint()
        {   
            for (int i = 0; i < PlayerHand.Count; ++i)
            {
                Console.WriteLine("You have a " + PlayerHand[i].CardValue + " of " + PlayerHand[i].CardSuit);

                if (i < PlayerHand.Count)
                {
                    Console.WriteLine ("&");
                }
            }

            Console.ReadLine();

        }

        public List<Card> Hit(List<Card> CardDeck, List<Card> PlayerHand)
        {
            PlayerHand.Add(CardDeck[1]);
            CardDeck.Remove(CardDeck[1]);

            return PlayerHand;
        }

    }
}
4

2 回答 2

2

您的Hit方法需要两个List<Card>参数,但您只传递一个Hand对象给它。

public List<Card> Hit(List<Card> CardDeck, List<Card> PlayerHand)
{
    ...
}

您需要做的是将Cardsmain 中的对象传递给Hand构造函数,以便 Hand 可以使用它:

public class Hand
{
    // You should make this private with a public property to guard it
    public List<Card> PlayerHand;

    // No reason to expose this to the outside
    private Deck cardDeck = new Deck();

    public Hand (Deck cards)
    {
        cardDeck = cards;
    }

    // There's nothing worth returning here, so make it void
    public void Hit()
    {
        // I would probably implement a method in the Deck class
        // so you could do something like (where RemoveNext returns the card removed):
        // playerHand.Add(cards.RemoveNext()); 
        playerHand.Add(CardDeck[1]);
        CardDeck.Remove(CardDeck[1]);
    }

你的Main样子是这样的:

public static void Main (string[] args)
{
    Deck cards = new Deck();
    Hand playerHand = new Hand(cards);

    Console.WriteLine("Welcome to Black Jack\n\nPress Enter To Start");
    Console.ReadLine();

    playerHand.Hit();
    playerHand.Hit();
    // I would rename this to PrintHand(). HandPrint is a noun.
    playerHand.HandPrint();
}
于 2013-03-18T02:53:21.487 回答
1

您遇到的错误是因为Hit()您的Hand类中的方法接受 2 个参数,而不是 1 个。它需要两个List<Card>()参数。

无论参数数量如何,您的代码都传递了一个Hand根本不起作用的对象。

于 2013-03-18T01:56:01.657 回答