IndentedTextWriter Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece um escritor de texto que pode indentar novas linhas por um token de sequência de tabulação.
public ref class IndentedTextWriter : System::IO::TextWriter
public class IndentedTextWriter : System.IO.TextWriter
type IndentedTextWriter = class
inherit TextWriter
Public Class IndentedTextWriter
Inherits TextWriter
- Herança
Exemplos
O exemplo de código seguinte demonstra o uso de um IndentedTextWriter para escrever texto em diferentes níveis de indentação.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
namespace IndentedTextWriterExample
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private string CreateMultilevelIndentString()
{
// Creates a TextWriter to use as the base output writer.
System.IO.StringWriter baseTextWriter = new System.IO.StringWriter();
// Create an IndentedTextWriter and set the tab string to use
// as the indentation string for each indentation level.
System.CodeDom.Compiler.IndentedTextWriter indentWriter = new IndentedTextWriter(baseTextWriter, " ");
// Sets the indentation level.
indentWriter.Indent = 0;
// Output test strings at stepped indentations through a recursive loop method.
WriteLevel(indentWriter, 0, 5);
// Return the resulting string from the base StringWriter.
return baseTextWriter.ToString();
}
private void WriteLevel(IndentedTextWriter indentWriter, int level, int totalLevels)
{
// Output a test string with a new-line character at the end.
indentWriter.WriteLine("This is a test phrase. Current indentation level: "+level.ToString());
// If not yet at the highest recursion level, call this output method for the next level of indentation.
if( level < totalLevels )
{
// Increase the indentation count for the next level of indented output.
indentWriter.Indent++;
// Call the WriteLevel method to write test output for the next level of indentation.
WriteLevel(indentWriter, level+1, totalLevels);
// Restores the indentation count for this level after the recursive branch method has returned.
indentWriter.Indent--;
}
else
{
// Outputs a string using the WriteLineNoTabs method.
indentWriter.WriteLineNoTabs("This is a test phrase written with the IndentTextWriter.WriteLineNoTabs method.");
}
// Outputs a test string with a new-line character at the end.
indentWriter.WriteLine("This is a test phrase. Current indentation level: "+level.ToString());
}
private void button1_Click(object sender, System.EventArgs e)
{
textBox1.Text = CreateMultilevelIndentString();
}
public Form1()
{
System.Windows.Forms.Button button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(8, 40);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(391, 242);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
button1.Location = new System.Drawing.Point(11, 8);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(229, 23);
button1.TabIndex = 1;
button1.Text = "Generate string using IndentedTextWriter";
button1.Click += new System.EventHandler(this.button1_Click);
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(407, 287);
this.Controls.Add(button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "IndentedTextWriter example";
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
}
}
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.ComponentModel
Imports System.IO
Imports System.Windows.Forms
Public Class Form1
Inherits System.Windows.Forms.Form
Private textBox1 As System.Windows.Forms.TextBox
Private Function CreateMultilevelIndentString() As String
' Create a TextWriter to use as the base output writer.
Dim baseTextWriter As New System.IO.StringWriter
' Create an IndentedTextWriter and set the tab string to use
' as the indentation string for each indentation level.
Dim indentWriter = New IndentedTextWriter(baseTextWriter, " ")
' Set the indentation level.
indentWriter.Indent = 0
' Output test strings at stepped indentations through a recursive loop method.
WriteLevel(indentWriter, 0, 5)
' Return the resulting string from the base StringWriter.
Return baseTextWriter.ToString()
End Function
Private Sub WriteLevel(ByVal indentWriter As IndentedTextWriter, ByVal level As Integer, ByVal totalLevels As Integer)
' Outputs a test string with a new-line character at the end.
indentWriter.WriteLine(("This is a test phrase. Current indentation level: " + level.ToString()))
' If not yet at the highest recursion level, call this output method for the next level of indentation.
If level < totalLevels Then
' Increase the indentation count for the next level of indented output.
indentWriter.Indent += 1
' Call the WriteLevel method to write test output for the next level of indentation.
WriteLevel(indentWriter, level + 1, totalLevels)
' Restores the indentation count for this level after the recursive branch method has returned.
indentWriter.Indent -= 1
Else
' Output a string using the WriteLineNoTabs method.
indentWriter.WriteLineNoTabs("This is a test phrase written with the IndentTextWriter.WriteLineNoTabs method.")
End If
' Outputs a test string with a new-line character at the end.
indentWriter.WriteLine(("This is a test phrase. Current indentation level: " + level.ToString()))
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
textBox1.Text = CreateMultilevelIndentString()
End Sub
Public Sub New()
Dim button1 As New System.Windows.Forms.Button
Me.textBox1 = New System.Windows.Forms.TextBox
Me.SuspendLayout()
Me.textBox1.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles)
Me.textBox1.Location = New System.Drawing.Point(8, 40)
Me.textBox1.Multiline = True
Me.textBox1.Name = "textBox1"
Me.textBox1.Size = New System.Drawing.Size(391, 242)
Me.textBox1.TabIndex = 0
Me.textBox1.Text = ""
button1.Location = New System.Drawing.Point(11, 8)
button1.Name = "button1"
button1.Size = New System.Drawing.Size(229, 23)
button1.TabIndex = 1
button1.Text = "Generate string using IndentedTextWriter"
AddHandler button1.Click, AddressOf Me.button1_Click
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(407, 287)
Me.Controls.Add(button1)
Me.Controls.Add(Me.textBox1)
Me.Name = "Form1"
Me.Text = "IndentedTextWriter example"
Me.ResumeLayout(False)
End Sub
<STAThread()> _
Shared Sub Main()
Application.Run(New Form1)
End Sub
End Class
Observações
IndentedTextWriter Estende A TextWriter fornecendo métodos que inserem uma sequência de tabulação e acompanham o nível atual de indentação. Texto formatado com múltiplos níveis de indentação é útil para código gerado, por isso esta classe é usada por implementações de geradores de código CodeDOM.
A sequência tab é a sequência em que consiste cada indentação. Normalmente, a sequência de tabulação contém espaços em branco.
Note
Essa classe contém uma demanda de link e uma demanda de herança no nível de classe que se aplica a todos os membros. A SecurityException é lançado quando o chamador imediato ou a classe derivada não tem permissão de confiança plena. Para detalhes sobre exigências de segurança, consulte Exigências de Ligação e Exigências de Herança.
Construtores
| Name | Description |
|---|---|
| IndentedTextWriter(TextWriter, String) |
Inicializa uma nova instância da IndentedTextWriter classe usando o escritor de texto especificado e a string de tabulação. |
| IndentedTextWriter(TextWriter) |
Inicializa uma nova instância da IndentedTextWriter classe usando o escritor de texto especificado e a string de tabulação predefinida. |
Campos
| Name | Description |
|---|---|
| CoreNewLine |
Armazena os caracteres da nova linha usados para isto |
| DefaultTabString |
Especifica a cadeia de tabulação por defeito. Este campo é constante. |
Propriedades
| Name | Description |
|---|---|
| Encoding |
Obtém a codificação para o escritor de texto usar. |
| FormatProvider |
Recebe um objeto que controla a formatação. (Herdado de TextWriter) |
| Indent |
Obtém ou define o número de espaços para indentar. |
| InnerWriter |
Obtém-nos TextWriter para usar. |
| NewLine |
Recebe ou define a nova personagem da linha para usar. |
Métodos
| Name | Description |
|---|---|
| Close() |
Fecha o documento para o qual está a ser escrito. |
| CreateObjRef(Type) |
Cria um objeto que contém toda a informação relevante necessária para gerar um proxy usado para comunicar com um objeto remoto. (Herdado de MarshalByRefObject) |
| Dispose() |
Liberta todos os recursos usados pelo TextWriter objeto. (Herdado de TextWriter) |
| Dispose(Boolean) |
Liberta os recursos não geridos usados pelo TextWriter e opcionalmente liberta os recursos geridos. (Herdado de TextWriter) |
| DisposeAsync() |
A libertação assíncrona de todos os recursos usados pelo TextWriter objeto. (Herdado de TextWriter) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| Flush() |
Despeja o jato. |
| FlushAsync() |
A-síncrono, limpa todos os buffers para o escritor atual e faz com que quaisquer dados em buffer sejam escritos no dispositivo subjacente. (Herdado de TextWriter) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetLifetimeService() |
Recupera o objeto de serviço de tempo de vida atual que controla a política de vida útil neste caso. (Herdado de MarshalByRefObject) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| InitializeLifetimeService() |
Obtém-se um objeto de serviço vitalício para controlar a apólice vitalícia neste caso. (Herdado de MarshalByRefObject) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto atual MarshalByRefObject . (Herdado de MarshalByRefObject) |
| OutputTabs() |
Produz a sequência tab uma vez para cada nível de indentação de acordo com a Indent propriedade. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
| Write(Boolean) |
Escreve a representação textual de um valor booleano no fluxo de texto. |
| Write(Char) |
Escreve um carácter no fluxo de texto. |
| Write(Char[], Int32, Int32) |
Escreve um subarray de caracteres no fluxo de texto. |
| Write(Char[]) |
Escreve um array de caracteres no fluxo de texto. |
| Write(Decimal) |
Escreve a representação textual de um valor decimal no fluxo de texto. (Herdado de TextWriter) |
| Write(Double) |
Escreve a representação textual de um Double no fluxo de texto. |
| Write(Int32) |
Escreve a representação textual de um inteiro no fluxo de texto. |
| Write(Int64) |
Escreve a representação textual de um inteiro de 8 bytes no fluxo de texto. |
| Write(Object) |
Escreve a representação textual de um objeto no fluxo de texto. |
| Write(ReadOnlySpan<Char>) |
Escreve um espaço de caracteres no fluxo de texto. (Herdado de TextWriter) |
| Write(Single) |
Escreve a representação de texto de um Single no fluxo de texto. |
| Write(String, Object, Object, Object) |
Escreve uma cadeia formatada no fluxo de texto, usando a mesma semântica do Format(String, Object, Object, Object) método. (Herdado de TextWriter) |
| Write(String, Object, Object) |
Escreve uma cadeia formatada, usando a mesma semântica especificada. |
| Write(String, Object) |
Escreve uma cadeia formatada, usando a mesma semântica especificada. |
| Write(String, Object[]) |
Escreve uma cadeia formatada, usando a mesma semântica especificada. |
| Write(String) |
Escreve a cadeia especificada no fluxo de texto. |
| Write(UInt32) |
Escreve a representação textual de um inteiro sem sinal de 4 bytes no fluxo de texto. (Herdado de TextWriter) |
| Write(UInt64) |
Escreve a representação textual de um inteiro sem sinal de 8 bytes no fluxo de texto. (Herdado de TextWriter) |
| WriteAsync(Char) |
Escreve um carácter no fluxo de texto de forma assíncrona. (Herdado de TextWriter) |
| WriteAsync(Char[], Int32, Int32) |
Escreve um subarray de caracteres no fluxo de texto de forma assíncrona. (Herdado de TextWriter) |
| WriteAsync(Char[]) |
Escreve um array de caracteres no fluxo de texto de forma assíncrona. (Herdado de TextWriter) |
| WriteAsync(ReadOnlyMemory<Char>, CancellationToken) |
De forma assíncrona, escreve uma região de memória de caracteres no fluxo de texto. (Herdado de TextWriter) |
| WriteAsync(String) |
Escreve uma string no fluxo de texto de forma assíncrona. (Herdado de TextWriter) |
| WriteLine() |
Escreve um terminador de linha. |
| WriteLine(Boolean) |
Escreve a representação textual de um Booleano, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(Char) |
Escreve um carácter, seguido de um terminador de linha, no fluxo de texto. |
| WriteLine(Char[], Int32, Int32) |
Escreve um subarray de caracteres, seguido de um terminador de linha, no fluxo de texto. |
| WriteLine(Char[]) |
Escreve um array de caracteres, seguido de um terminador de linha, no fluxo de texto. |
| WriteLine(Decimal) |
Escreve a representação textual de um valor decimal no fluxo de texto, seguida de um terminador de linha. (Herdado de TextWriter) |
| WriteLine(Double) |
Escreve a representação textual de um Double, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(Int32) |
Escreve a representação textual de um inteiro, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(Int64) |
Escreve a representação de texto de um inteiro de 8 bytes, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(Object) |
Escreve a representação textual de um objeto, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(ReadOnlySpan<Char>) |
Escreve a representação de texto de um espaço de caracteres no fluxo de texto, seguida de um terminador de linha. (Herdado de TextWriter) |
| WriteLine(Single) |
Escreve a representação de texto de um Single, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(String, Object, Object, Object) |
Escreve uma cadeia formatada e uma nova linha no fluxo de texto, usando a mesma semântica que Format(String, Object). (Herdado de TextWriter) |
| WriteLine(String, Object, Object) |
Escreve uma cadeia formatada, seguida de um terminador de linha, usando a mesma semântica especificada. |
| WriteLine(String, Object) |
Escreve uma cadeia formatada, seguida de um terminador de linha, usando a mesma semântica especificada. |
| WriteLine(String, Object[]) |
Escreve uma cadeia formatada, seguida de um terminador de linha, usando a mesma semântica especificada. |
| WriteLine(String) |
Escreve a cadeia especificada, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(UInt32) |
Escreve a representação de texto de um UInt32, seguida de um terminador de linha, no fluxo de texto. |
| WriteLine(UInt64) |
Escreve a representação de texto de um inteiro sem sinal de 8 bytes no fluxo de texto, seguida de um terminador de linha. (Herdado de TextWriter) |
| WriteLineAsync() |
Escreve assíncronamente um terminador de linha no fluxo de texto. (Herdado de TextWriter) |
| WriteLineAsync(Char) |
Escreve assíncronamente um carácter no fluxo de texto, seguido de um terminador de linha. (Herdado de TextWriter) |
| WriteLineAsync(Char[], Int32, Int32) |
O Assíncrono escreve um subarray de caracteres no fluxo de texto, seguido de um terminador de linha. (Herdado de TextWriter) |
| WriteLineAsync(Char[]) |
Escreve assíncronamente um array de caracteres no fluxo de texto, seguido de um terminador de linha. (Herdado de TextWriter) |
| WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken) |
Escreve assíncronamente a representação de texto de uma região de memória de caracteres no fluxo de texto, seguida de um terminador de linha. (Herdado de TextWriter) |
| WriteLineAsync(String) |
Escreve assíncronamente uma string no fluxo de texto, seguida de um terminador de linha. (Herdado de TextWriter) |
| WriteLineNoTabs(String) |
Escreve a string especificada numa linha sem tabulações. |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| IDisposable.Dispose() |
Para uma descrição deste elemento, veja Dispose(). (Herdado de TextWriter) |
Métodos da Extensão
| Name | Description |
|---|---|
| ConfigureAwait(IAsyncDisposable, Boolean) |
Configura como aguarda nas tarefas devolvidas de um descartável assíncrono será realizada. |