打印foreach列表<;字符串>;在单独类别(C#)中

本文关键字:单独类 gt 列表 foreach lt 字符串 打印 | 更新日期: 2023-09-27 18:25:07

我想我对如何在另一个类中显示我所做的内容感到困惑。例如,我写了一个句子列表类,如下所示。在我的演示类中,当用户在菜单中选择"句子列表"选项时,它将调用"句子列表者"类,运行该类,并输出列表的结果。我该怎么做?

我知道使用ToString我可以调用那个特定的ToString,并让它返回我需要的任何东西,但我如何使用forecach循环来为列表中的每个项目显示它,或者显示列表中的特定项目,即列表项目4。我用ToString试过,但没能弄清楚。

所以,假设我的Demo类处理一个开关案例,那么在选择开关案例后,它会是什么?

现在我知道我的句子列表课不起作用,因为它有foreach循环。我之所以把它放在那里,是因为我试图通过调用foreach循环来一步一步地解决我的困境,或者只让句子列表起作用。我是C#的新手,还在学习如何做一些基本的函数。

句子列表类

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
}
}

打印foreach列表<;字符串>;在单独类别(C#)中

不确定我是否正确理解了你,但我的看法是:
您希望在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"));的东西。