【问题标题】:Print foreach List<string> in Separate Class (C#)在单独的类中打印 foreach List<string> (C#)
【发布时间】:2012-02-18 17:36:21
【问题描述】:

我想我对如何展示我在另一堂课上所做的感到困惑。例如,我编写了一个 SentenceList 类,如下所示。在我的演示类中,当用户在菜单中选择 SentenceList 选项时,它会调用 Sentencelist 类,运行该类,并输出列表的结果。我该怎么做?

我知道使用 ToString 我可以调用特定的 ToString 并让它返回我需要的任何内容,但是如何使用 forecach 循环为列表中的每个项目显示它,或显示列表中的特定项目IE。列表项 4。我用 ToString 尝试过,但无法弄清楚。

所以假设我的 Demo 类使用 switch case,那么在选择 switch case 之后会是什么?

现在我知道我的 SentenceList 类由于其中的 foreach 循环而无法工作。我把它放在那里是因为我试图通过创建一个需要调用的 foreach 循环或只使 SentenceList 工作来一步一步解决我的困境。我是 C# 新手,仍在学习如何执行一些基本功能。

SentenceList 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace StringHandling
{
class SentenceList
{
    private String origText { get; set; }
    public List<string> tokens { get; private set; }
    public int numWords { get; private set; }
    public int avgLength { get; private set; }

    public string delims = ".?!";

    public SentenceList ( string OrigText )
    {
        origText = OrigText;
        tokens = Utility.Tokenize ( OrigText , delims );
    }

    public int CountWords ( string s )
    {
        MatchCollection collection = Regex.Matches ( s , @"[\S]+" );
        return collection.Count;
    }

    public int AverageWords ( string s )
    {
        int avg = 0;
        string[] words = s.Split ( ' ' );
        foreach ( string word in words )
        {
            avg += word.Length;
        }
        avg = avg / ( CountWords ( origText ) );
        return avg;
    }

    public static string ToString ( string format )
    {
        var sb = new StringBuilder ( );
        var i = 0;
        foreach ( string a in tokens )
            {
                i++;
                numWords = CountWords ( a );
                avgLength = AverageWords ( a );
                sb.Append ( string.Format ( "Sentence {0}. \n\n {1} \n\n Number of Words: {2}        Average Word Length: {3}" , i , a , numWords , avgLength ) ).AppendLine ( );
            }
        return sb.ToString ( );
    }  

}
}

演示课

using System;
using System.IO;
using System.Windows.Forms;

namespace StringHandling
{
enum Choices
{
    TEXT = 1 ,
    DISTINCTWORD ,
    WORD ,
    SENTENCE ,
    SENTENCELIST ,
    PARAGRAPH ,
    PARAGRAPHLIST ,
    QUIT
}


class Demo
{
    static void Main ( string [ ] args )
    {
        Console.BackgroundColor = ConsoleColor.White;
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.Title = "String Handling Demonstration Application";
        Console.Clear ( );

        Utility.WelcomeMessage ( "Hello" );

        string filePath = "text.txt";

        if ( !File.Exists ( filePath ) )
        {
            throw new FileNotFoundException ( " The file '{0}' was not found and could not be opened." , filePath );
        }
        StreamReader sr = File.OpenText ( filePath );
        string origText = sr.ReadToEnd ( );

        Menu menu = new Menu ( "String Choices" );
        menu = menu + "Text" + "DistinctWords" + "Words" + "Sentence" + "SentenceList" + "Paragraph" + "ParagraphList" + "Quit";

        Choices choice = ( Choices ) menu.GetChoice ( );
        while ( choice != Choices.QUIT )
        {
            switch ( choice )
            {
                case Choices.TEXT:
                    Console.WriteLine ( "You selected TEXT" );
                    //Text text1 = new Text ( origText );
                    //Console.WriteLine ( "\nThe original text you entered was:\n\n {0}" , Text.ToString( ) );
                    Utility.PressAnyKey ( );
                    break;

                case Choices.DISTINCTWORD:
                    Console.WriteLine ( "You selected DISTINCTWORD" );
                    Utility.PressAnyKey ( );
                    break;

                case Choices.WORD:
                    Console.WriteLine ( "You selected WORD" );
                    Utility.PressAnyKey ( );
                    break;

                case Choices.SENTENCE:
                    Console.WriteLine ( "You selected SENTENCE" );
                    Sentence sent1 = new Sentence ( origText );
                    Console.WriteLine ( "Stuff" );
                    Utility.PressAnyKey ( );
                    break;

                case Choices.SENTENCELIST:
                    Console.WriteLine ( "You selected SENTENCELIST" );
                    SentenceList sent2 = new SentenceList ( origText );
                    Console.WriteLine ( SentenceList.ToString ( "" ) );
                    break;

                case Choices.PARAGRAPH:
                    Console.WriteLine ( "You selected PARAGRAPH" );
                    Utility.PressAnyKey ( );
                    break;

                case Choices.PARAGRAPHLIST:
                    Console.WriteLine ( "You selected PARAGRAPHLIST" );
                    Utility.PressAnyKey ( );
                    break;
            }  // end of switch

            choice = ( Choices ) menu.GetChoice ( );
        }  // end of while

        Utility.GoodbyeMessage ( "Thank you for using our application." );

    }  // end of main
}
}

【问题讨论】:

  • 您在寻找类似String.Join(",",tokens) 的东西吗?
  • 我无法理解您遇到的确切问题。此外,您提供的代码无法编译,在类的中间,方法之外有一个foreach 循环。
  • No 在我的 Demo 类中,这是我想在 foreach 循环中打印出句子列表类的第二段代码。 foreach 循环位于 SentenceClass 的中间,因为我试图弄清楚它好像句子类会单独运行。所以我试图弄清楚使用 sentencelist 类打印段落中的所有句子
  • 我在这个问题上继续工作了几个小时,但没有成功。也许我在这里也不够清楚。我想弄清楚的是如何将我的 SentenceList 类中的 Foreach 循环放入我的 Demo

标签: c# .net arrays visual-studio visual-studio-2010


【解决方案1】:

不确定我是否理解正确,但这是我的看法:
您想在Demo 类中显示SentenceList 类中列表项的各种字符串表示形式。如果是这种情况,我会使用一个接受格式参数的ToString() 方法,然后在该参数上写一个switch-case。在我的SentenceList 类中如下所示:

public string ToString(string format)
{
    var sb = new StringBuilder();
    switch (format)
    {
        case "a":
            var i = 0;
            foreach (string a in tokens)
            {   
                i++;
                numWords = CountWords(a);
                avgLength = AverageWords (a);
                sb.Append(string.Format("Sentence {0}. \n\n {1} \n\n Number of Words: {2}        Average Word Length: {3}" , i , a , numWords , avgLength)).AppendLine();
            }
          break;
        case "b":
          // Another representation here.
          break;
        default:
          // default format
          break;
    }

return sb.ToString();
}  

并在我的Demo 类中使用Console.WriteLine(mySentenceList.ToString("a")); 之类的东西。

【讨论】:

  • 我相信这回答了我的大部分问题。不完全是我的意思,但我认为它回答了我试图弄清楚的问题,所以谢谢。如果我想在列表中打印特定标记,我将如何使用它?喜欢列表项 3 吗?
  • 好吧,也许是另一个接受索引的重载。喜欢public string ToString(string format, int index)
  • 所以我仍然没有得到这个我添加了我的整个演示代码我得到的错误是在 vs2010 中 - 错误 1 ​​非静态字段、方法或属性'StringHandling.SentenceList 需要对象引用.tokens.get' I:\Class\CSCI 2210\Projects\StringHandling\StringHandling\SentenceList.cs 64 35 StringHandling
  • 检查令牌的使用情况。似乎它在初始化之前在某处使用(可能是成员上的 foreach 列表)。一种快速解决方法可能是在 SentenceList ctor 中添加 tokens = new List&lt;string&gt;()
  • 好的,非常感谢你,我能够使用所有这些来解决这个问题。很棒的学习体验!
猜你喜欢
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多