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

标签 c# string class

我的作业基于硬币和纸牌游戏,非常简单。我们得到了一些完整的和一些不完整的文件。我想做的是从一个类 (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;
    }

来自 hand.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);

关于c# - 从一个类到另一个类调用字符串方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10886375/

相关文章:

c# - 为什么我不能在隐式转换时返回接口(interface),而 ExpandoObject 可以?

c# - 在VBA中编译支持声明函数的dll

c# - 负向查找后面带有未知数量的空格

python - CPython 中的字符串乘法是如何实现的?

c# - 通用查找函数作为参数

c# - 无法将土耳其语字符从文本文件读取到字符串数组

ruby - 如何将逗号分隔的字符串转换为数组?

c++ - 为什么我的类构造函数没有按预期工作?

android - 使用 fragment 时应用程序崩溃

java - 如何在 Eclipse 中处理仅由 .class 文件组成的项目?