📜  C#StringReader

📅  最后修改于: 2020-10-31 04:17:15             🧑  作者: Mango

C#StringReader类

StringReader类用于读取由StringWriter类编写的数据。它是TextReader类的子类。它使我们能够同步或异步读取字符串。它提供了构造函数和方法来执行读取操作。

C#StringReader签名

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StringReader : TextReader

C#StringReader构造函数

StringReader具有以下构造函数。

Constructors Description
StringReader(String) Initializes a new instance of the StringReader class that reads from the specified string.

C#StringReader方法

以下是StringReader类的方法。

Method Description
Close() It is used to close the StringReader.
Dispose() It is used to release all resources used by the TextReader object.
Equals(Object) It determines whether the specified object is equal to the current object or not.
Finalize() It allows an object to try to free resources and perform other cleanup operations.
GetHashCode() It serves as the default hash function.
GetType() It is used to get the type of the current instance.
Peek() It is used to return the next available character but does not consume it.
Read() It is used to read the next character from the input string.
ReadLine() It is used to read a line of characters from the current string.
ReadLineAsync() It is used to read a line of characters asynchronously from the current string.
ReadToEnd() It is used to read all the characters from the current position to the end of the string.
ReadToEndAsync() It is used to read all the characters from the current position to the end of the string asynchronously.
ToString() It is used to return a string that represents the current object.

C#StringReader示例

在下面的示例中,StringWriter类用于写入字符串信息,而StringReader类用于读取由StringWriter类编写的字符串。

using System;
using System.IO;
namespace CSharpProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            StringWriter str = new StringWriter();
            str.WriteLine("Hello, this message is read by StringReader class");
            str.Close();
            // Creating StringReader instance and passing StringWriter
            StringReader reader = new StringReader(str.ToString());
            // Reading data
            while (reader.Peek() > -1)
            {
                Console.WriteLine(reader.ReadLine());
            }
        }
    }
}

输出:

Hello, this message is read by StringReader class