从一个类调用字符串方法到另一个类

本文关键字:调用 字符串 另一个 方法 一个 | 更新日期: 2023-09-27 18:36:11

我有这个基于硬币和纸牌游戏的任务,它非常简化。我们得到了一些完整的和一些不完整的文件。我正在尝试做的是从一个类(card.cs)调用另一个类(hand.cs)中的方法(实际上是字符串)。

这是来自 card.cs 的字符串方法:

public string ToString(bool shortFormat, bool displaySuit)
    {
        string returnString;
        // Describe the FaceValue.
        FaceValue faceValue = GetFaceValue();
        string faceValueAsString = faceValue.ToString();
        if (shortFormat) {
            if (faceValue <= FaceValue.Ten) {
                faceValueAsString = (faceValue - FaceValue.Two + 2).ToString();
            } else {
                faceValueAsString = faceValueAsString.Substring(0, 1);
            }
        }
        returnString = faceValueAsString;
        // Describe the Suit.
        if (displaySuit) {
            string suit = GetSuit().ToString();
            if (shortFormat) {
                suit = suit.Substring(0, 1);
                returnString += suit;
            } else {
                returnString += " of " + suit;
            }
        }
        return returnString;
    }

和手.cs(仅限 ToString 字符串/方法,此文件中还有其他函数处理创建手牌(列出命名卡)并向其添加卡。

/// <summary>
    /// Outputs the hand of cards.
    /// See the ToString method in the Card class for a description of 
    /// the two parameters: shortFormat and displaySuit.
    /// Pre: true
    /// Post: Displayed the hand of cards.
    /// </summary>
    public void DisplayHand(bool shortFormat, bool displaySuit) {
        //
        //**************** CODE NEEDS TO BE ADDED**********************
        // Should be able to call the ToString method in the Card class,
        // as part of this.
        //
    } // end DisplayHand

它们是我为作业获得的未经编辑的文件。我想知道的是如何在DisplayHand(shortFormat, displaySuit)中使用TwoString(shortFormat, displaySuit)。在一个阶段,我有一个单独的列表来放置字符串值,但后来它被删除了,试图将文件恢复到原始文件。我不太确定稍后在游戏中如何使用它,但我想如果我可以让它与列表一起运行,然后将列表更改为字符串或数组或任何稍后可以轻松完成的内容。一旦我知道如何调用这个字符串,我应该能够修改我必须调用的所有其他字符串和整数的代码。

从一个类调用字符串方法到另一个类

你需要

一个Card来调用ToString。我假设你会这样做:

foreach (Card card in this.Cards) { ... } // Loop through cards in this hand.

如果不了解代码,我无法确切地告诉您如何。

有了Card(在 card 变量中)后,像这样调用ToString

string str = card.ToString(true, true);