Console.WriteLine Método
Definición
Escribe los datos especificados, seguidos del terminador de línea actual, en el flujo de salida estándar.Writes the specified data, followed by the current line terminator, to the standard output stream.
Sobrecargas
| WriteLine(String, Object, Object) |
Escribe la representación de texto de los objetos especificados, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information. |
| WriteLine(String) |
Escribe el valor de cadena especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the specified string value, followed by the current line terminator, to the standard output stream. |
| WriteLine(Char[], Int32, Int32) |
Escribe la submatriz de caracteres Unicode especificada, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the specified subarray of Unicode characters, followed by the current line terminator, to the standard output stream. |
| WriteLine(String, Object[]) |
Escribe la representación de texto de la matriz de objetos especificada, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information. |
| WriteLine(String, Object) |
Escribe la representación de texto del objeto especificado, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information. |
| WriteLine(UInt64) |
Escribe la representación de texto del valor entero de 64 bits sin signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line terminator, to the standard output stream. |
| WriteLine(UInt32) |
Escribe la representación de texto del valor entero de 32 bits sin signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream. |
| WriteLine(Single) |
Escribe la representación de texto del valor de punto flotante de precisión sencilla especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified single-precision floating-point value, followed by the current line terminator, to the standard output stream. |
| WriteLine(Decimal) |
Escribe la representación de texto del valor Decimal especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified Decimal value, followed by the current line terminator, to the standard output stream. |
| WriteLine(Int64) |
Escribe la representación de texto del valor entero de 64 bits con signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 64-bit signed integer value, followed by the current line terminator, to the standard output stream. |
| WriteLine(Int32) |
Escribe la representación de texto del valor entero de 32 bits con signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 32-bit signed integer value, followed by the current line terminator, to the standard output stream. |
| WriteLine(Double) |
Escribe la representación de texto del valor de punto flotante de precisión doble especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified double-precision floating-point value, followed by the current line terminator, to the standard output stream. |
| WriteLine(Char[]) |
Escribe la matriz de caracteres Unicode especificada, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream. |
| WriteLine(Char) |
Escribe el carácter Unicode especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream. |
| WriteLine(Boolean) |
Escribe la representación de texto del valor booleano especificado, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified Boolean value, followed by the current line terminator, to the standard output stream. |
| WriteLine() |
Escribe el terminador de línea actual en el flujo de salida estándar.Writes the current line terminator to the standard output stream. |
| WriteLine(String, Object, Object, Object) |
Escribe la representación de texto de los objetos especificados, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information. |
| WriteLine(Object) |
Escribe la representación de texto del objeto especificado, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream. |
| WriteLine(String, Object, Object, Object, Object) |
Escribe la representación de texto de los objetos especificados y la lista de parámetros de longitud variable, seguidas del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified objects and variable-length parameter list, followed by the current line terminator, to the standard output stream using the specified format information. |
Comentarios
El terminador de línea predeterminado es una cadena cuyo valor es un retorno de carro seguido de un salto de línea ("\r\n" en C#, o vbCrLf en Visual Basic).The default line terminator is a string whose value is a carriage return followed by a line feed ("\r\n" in C#, or vbCrLf in Visual Basic). Puede cambiar el terminador de línea estableciendo la TextWriter.NewLine propiedad de la Out propiedad en otra cadena.You can change the line terminator by setting the TextWriter.NewLine property of the Out property to another string.
WriteLine(String, Object, Object)
Escribe la representación de texto de los objetos especificados, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
public:
static void WriteLine(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static void WriteLine (string format, object? arg0, object? arg1);
public static void WriteLine (string format, object arg0, object arg1);
static member WriteLine : string * obj * obj -> unit
Public Shared Sub WriteLine (format As String, arg0 As Object, arg1 As Object)
Parámetros
- format
- String
Cadena de formato compuesto.A composite format string.
- arg0
- Object
Primer objeto que se va a escribir con format.The first object to write using format.
- arg1
- Object
Segundo objeto que se va a escribir con format.The second object to write using format.
Excepciones
Error de E/S.An I/O error occurred.
format es null.format is null.
La especificación de formato de format no es válida.The format specification in format is invalid.
Ejemplos
En el ejemplo siguiente se muestran los especificadores de formato estándar para números, fechas y enumeraciones.The following example demonstrates the standard formatting specifiers for numbers, dates, and enumerations.
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using namespace System;
public enum class Color {Yellow = 1, Blue, Green};
int main()
{
DateTime thisDate = DateTime::Now;
Console::Clear();
// Format a negative integer or floating-point number in various ways.
Console::WriteLine("Standard Numeric Format Specifiers");
Console::WriteLine(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
// Format the current date in various ways.
Console::WriteLine("Standard DateTime Format Specifiers");
Console::WriteLine(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal full date/time: {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
// Format a Color enumeration value in various ways.
Console::WriteLine("Standard Enumeration Format Specifiers");
Console::WriteLine(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color::Green);
};
/*
This code example produces the following results:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using System;
class Sample
{
enum Color {Yellow = 1, Blue, Green};
static DateTime thisDate = DateTime.Now;
public static void Main()
{
Console.Clear();
// Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers");
Console.WriteLine(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
// Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers");
Console.WriteLine(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal full date/time: {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
// Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers");
Console.WriteLine(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color.Green);
}
}
/*
This code example produces the following results:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/
' This code example demonstrates the Console.WriteLine() method.
' Formatting for this example uses the "en-US" culture.
Class Sample
Public Enum Color
Yellow = 1
Blue = 2
Green = 3
End Enum 'Color
Private Shared thisDate As DateTime = DateTime.Now
Public Shared Sub Main()
Console.Clear()
' Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers")
Console.WriteLine("(C) Currency: . . . . . . . . {0:C}" & vbCrLf & _
"(D) Decimal:. . . . . . . . . {0:D}" & vbCrLf & _
"(E) Scientific: . . . . . . . {1:E}" & vbCrLf & _
"(F) Fixed point:. . . . . . . {1:F}" & vbCrLf & _
"(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(N) Number: . . . . . . . . . {0:N}" & vbCrLf & _
"(P) Percent:. . . . . . . . . {1:P}" & vbCrLf & _
"(R) Round-trip: . . . . . . . {1:R}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
- 123, - 123.45F)
' Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers")
Console.WriteLine("(d) Short date: . . . . . . . {0:d}" & vbCrLf & _
"(D) Long date:. . . . . . . . {0:D}" & vbCrLf & _
"(t) Short time: . . . . . . . {0:t}" & vbCrLf & _
"(T) Long time:. . . . . . . . {0:T}" & vbCrLf & _
"(f) Full date/short time: . . {0:f}" & vbCrLf & _
"(F) Full date/long time:. . . {0:F}" & vbCrLf & _
"(g) General date/short time:. {0:g}" & vbCrLf & _
"(G) General date/long time: . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(M) Month:. . . . . . . . . . {0:M}" & vbCrLf & _
"(R) RFC1123:. . . . . . . . . {0:R}" & vbCrLf & _
"(s) Sortable: . . . . . . . . {0:s}" & vbCrLf & _
"(u) Universal sortable: . . . {0:u} (invariant)" & vbCrLf & _
"(U) Universal full date/time: {0:U}" & vbCrLf & _
"(Y) Year: . . . . . . . . . . {0:Y}" & vbCrLf, _
thisDate)
' Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers")
Console.WriteLine("(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)" & vbCrLf & _
"(D) Decimal number: . . . . . {0:D}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
Color.Green)
End Sub
End Class
'
'This code example produces the following results:
'
'Standard Numeric Format Specifiers
'(C) Currency: . . . . . . . . ($123.00)
'(D) Decimal:. . . . . . . . . -123
'(E) Scientific: . . . . . . . -1.234500E+002
'(F) Fixed point:. . . . . . . -123.45
'(G) General:. . . . . . . . . -123
' (default):. . . . . . . . -123 (default = 'G')
'(N) Number: . . . . . . . . . -123.00
'(P) Percent:. . . . . . . . . -12,345.00 %
'(R) Round-trip: . . . . . . . -123.45
'(X) Hexadecimal:. . . . . . . FFFFFF85
'
'Standard DateTime Format Specifiers
'(d) Short date: . . . . . . . 6/26/2004
'(D) Long date:. . . . . . . . Saturday, June 26, 2004
'(t) Short time: . . . . . . . 8:11 PM
'(T) Long time:. . . . . . . . 8:11:04 PM
'(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
'(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
'(g) General date/short time:. 6/26/2004 8:11 PM
'(G) General date/long time: . 6/26/2004 8:11:04 PM
' (default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
'(M) Month:. . . . . . . . . . June 26
'(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
'(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
'(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
'(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
'(Y) Year: . . . . . . . . . . June, 2004
'
'Standard Enumeration Format Specifiers
'(G) General:. . . . . . . . . Green
' (default):. . . . . . . . Green (default = 'G')
'(F) Flags:. . . . . . . . . . Green (flags or integer)
'(D) Decimal number: . . . . . 3
'(X) Hexadecimal:. . . . . . . 00000003
'
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
Este método usa la característica de formato compuesto de .net para convertir el valor de un objeto en su representación de texto e incrustar esa representación en una cadena.This method uses the composite formatting feature of .NET to convert the value of an object to its text representation and embed that representation in a string. La cadena resultante se escribe en el flujo de salida.The resulting string is written to the output stream.
El format parámetro se compone de cero o más ejecuciones de texto combinadas con cero o más marcadores de posición indizados, denominados elementos de formato, que corresponden a un objeto de la lista de parámetros de este método.The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. El proceso de formato reemplaza cada elemento de formato con la representación de texto del valor del objeto correspondiente.The formatting process replaces each format item with the text representation of the value of the corresponding object.
La sintaxis de un elemento de formato es { index[ , alignment] [ : FormatString] } , que especifica un índice obligatorio, la longitud opcional y la alineación del texto con formato, y una cadena opcional de caracteres especificadores de formato que rigen cómo se da formato al valor del objeto correspondiente.The syntax of a format item is {index[,alignment][:formatString]}, which specifies a mandatory index, the optional length and alignment of the formatted text, and an optional string of format specifier characters that govern how the value of the corresponding object is formatted.
.NET proporciona una gran compatibilidad con el formato, que se describe con más detalle en los siguientes temas de formato..NET provides extensive formatting support, which is described in greater detail in the following formatting topics.
Para obtener más información sobre la característica de formato compuesto compatible con métodos como Format , AppendFormat y algunas sobrecargas de WriteLine , vea formato compuesto.For more information about the composite formatting feature supported by methods such as Format, AppendFormat, and some overloads of WriteLine, see Composite Formatting.
Para obtener más información sobre los especificadores de formato numérico, vea cadenas de formato numérico estándar y cadenas de formato numérico personalizado.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Para obtener más información sobre los especificadores de formato de fecha y hora, vea cadenas con formato de fecha y hora estándar y cadenas con formato de fecha y hora personalizado.For more information about date and time format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Para obtener más información sobre los especificadores de formato de enumeración, vea cadenas de formato de enumeración.For more information about enumeration format specifiers, see Enumeration Format Strings.
Para obtener más información sobre el formato, vea aplicar formato a tipos.For more information about formatting, see Formatting Types.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
- Read()
- ReadLine()
- Write(String, Object)
- Aplicar formato a tipos en .NETFormatting Types in .NET
- Formatos compuestosComposite Formatting
Se aplica a
WriteLine(String)
Escribe el valor de cadena especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the specified string value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(System::String ^ value);
public static void WriteLine (string? value);
public static void WriteLine (string value);
static member WriteLine : string -> unit
Public Shared Sub WriteLine (value As String)
Parámetros
- value
- String
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
En el ejemplo se cambia el terminador de línea de su valor predeterminado de "\r\n" o vbCrLf a "\r\n\r\n" o vbCrLf + vbCrLf .The example changes the line terminator from its default value of "\r\n" or vbCrLf to "\r\n\r\n" or vbCrLf + vbCrLf. A continuación, llama a los WriteLine() WriteLine(String) métodos y para mostrar la salida en la consola.It then calls the WriteLine() and WriteLine(String) methods to display output to the console.
using namespace System;
void main()
{
array<String^>^ lines = gcnew array<String^> { "This is the first line.",
"This is the second line." };
// Output the lines using the default newline sequence.
Console::WriteLine("With the default new line characters:");
Console::WriteLine();
for each (String^ line in lines)
Console::WriteLine(line);
Console::WriteLine();
// Redefine the newline characters to double space.
Console::Out->NewLine = "\r\n\r\n";
// Output the lines using the new newline sequence.
Console::WriteLine("With redefined new line characters:");
Console::WriteLine();
for each (String^ line in lines)
Console::WriteLine(line);
}
// The example displays the following output:
// With the default new line characters:
//
// This is the first line.
// This is the second line.
//
// With redefined new line characters:
//
//
//
// This is the first line.
//
// This is the second line.
string[] lines = { "This is the first line.",
"This is the second line." };
// Output the lines using the default newline sequence.
Console.WriteLine("With the default new line characters:");
Console.WriteLine();
foreach (string line in lines)
Console.WriteLine(line);
Console.WriteLine();
// Redefine the newline characters to double space.
Console.Out.NewLine = "\r\n\r\n";
// Output the lines using the new newline sequence.
Console.WriteLine("With redefined new line characters:");
Console.WriteLine();
foreach (string line in lines)
Console.WriteLine(line);
// The example displays the following output:
// With the default new line characters:
//
// This is the first line.
// This is the second line.
//
// With redefined new line characters:
//
//
//
// This is the first line.
//
// This is the second line.
Module Example
Public Sub Main()
Dim lines() As String = { "This is the first line.", _
"This is the second line." }
' Output the lines using the default newline sequence.
Console.WriteLine("With the default new line characters:")
Console.WriteLine()
For Each line As String In lines
Console.WriteLine(line)
Next
Console.WriteLine()
' Redefine the newline characters to double space.
Console.Out.NewLine = vbCrLf + vbCrLf
' Output the lines using the new newline sequence.
Console.WriteLine("With redefined new line characters:")
Console.WriteLine()
For Each line As String In lines
Console.WriteLine(line)
Next
End Sub
End Module
' The example displays the following output:
' With the default new line characters:
'
' This is the first line.
' This is the second line.
'
' With redefined new line characters:
'
'
'
' This is the first line.
'
' This is the second line.
Comentarios
Si value es null , solo se escribe el terminador de línea en el flujo de salida estándar.If value is null, only the line terminator is written to the standard output stream.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine() método.For more information about the line terminator, see the Remarks section of the WriteLine() method.
Consulte también
Se aplica a
WriteLine(Char[], Int32, Int32)
Escribe la submatriz de caracteres Unicode especificada, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the specified subarray of Unicode characters, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(cli::array <char> ^ buffer, int index, int count);
public static void WriteLine (char[] buffer, int index, int count);
static member WriteLine : char[] * int * int -> unit
Public Shared Sub WriteLine (buffer As Char(), index As Integer, count As Integer)
Parámetros
- buffer
- Char[]
Matriz de caracteres Unicode.An array of Unicode characters.
- index
- Int32
Posición inicial en buffer.The starting position in buffer.
- count
- Int32
Número de caracteres que se van a escribir.The number of characters to write.
Excepciones
buffer es null.buffer is null.
index o count es menor que cero.index or count is less than zero.
index más count especifica una posición que no está dentro de buffer.index plus count specify a position that is not within buffer.
Error de E/S.An I/O error occurred.
Comentarios
Este método escribe count caracteres index a partir de la posición de buffer en el flujo de salida estándar.This method writes count characters starting at position index of buffer to the standard output stream.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(String, Object[])
Escribe la representación de texto de la matriz de objetos especificada, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information.
public:
static void WriteLine(System::String ^ format, ... cli::array <System::Object ^> ^ arg);
public static void WriteLine (string format, params object?[]? arg);
public static void WriteLine (string format, params object[] arg);
static member WriteLine : string * obj[] -> unit
Public Shared Sub WriteLine (format As String, ParamArray arg As Object())
Parámetros
- format
- String
Cadena de formato compuesto.A composite format string.
- arg
- Object[]
Matriz de objetos que se va a escribir con format.An array of objects to write using format.
Excepciones
Error de E/S.An I/O error occurred.
format o arg es null.format or arg is null.
La especificación de formato de format no es válida.The format specification in format is invalid.
Ejemplos
En el ejemplo siguiente se muestran los especificadores de formato estándar para números, fechas y enumeraciones.The following example demonstrates the standard formatting specifiers for numbers, dates, and enumerations.
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using namespace System;
public enum class Color {Yellow = 1, Blue, Green};
int main()
{
DateTime thisDate = DateTime::Now;
Console::Clear();
// Format a negative integer or floating-point number in various ways.
Console::WriteLine("Standard Numeric Format Specifiers");
Console::WriteLine(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
// Format the current date in various ways.
Console::WriteLine("Standard DateTime Format Specifiers");
Console::WriteLine(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal full date/time: {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
// Format a Color enumeration value in various ways.
Console::WriteLine("Standard Enumeration Format Specifiers");
Console::WriteLine(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color::Green);
};
/*
This code example produces the following results:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using System;
class Sample
{
enum Color {Yellow = 1, Blue, Green};
static DateTime thisDate = DateTime.Now;
public static void Main()
{
Console.Clear();
// Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers");
Console.WriteLine(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
// Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers");
Console.WriteLine(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal full date/time: {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
// Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers");
Console.WriteLine(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color.Green);
}
}
/*
This code example produces the following results:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/
' This code example demonstrates the Console.WriteLine() method.
' Formatting for this example uses the "en-US" culture.
Class Sample
Public Enum Color
Yellow = 1
Blue = 2
Green = 3
End Enum 'Color
Private Shared thisDate As DateTime = DateTime.Now
Public Shared Sub Main()
Console.Clear()
' Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers")
Console.WriteLine("(C) Currency: . . . . . . . . {0:C}" & vbCrLf & _
"(D) Decimal:. . . . . . . . . {0:D}" & vbCrLf & _
"(E) Scientific: . . . . . . . {1:E}" & vbCrLf & _
"(F) Fixed point:. . . . . . . {1:F}" & vbCrLf & _
"(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(N) Number: . . . . . . . . . {0:N}" & vbCrLf & _
"(P) Percent:. . . . . . . . . {1:P}" & vbCrLf & _
"(R) Round-trip: . . . . . . . {1:R}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
- 123, - 123.45F)
' Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers")
Console.WriteLine("(d) Short date: . . . . . . . {0:d}" & vbCrLf & _
"(D) Long date:. . . . . . . . {0:D}" & vbCrLf & _
"(t) Short time: . . . . . . . {0:t}" & vbCrLf & _
"(T) Long time:. . . . . . . . {0:T}" & vbCrLf & _
"(f) Full date/short time: . . {0:f}" & vbCrLf & _
"(F) Full date/long time:. . . {0:F}" & vbCrLf & _
"(g) General date/short time:. {0:g}" & vbCrLf & _
"(G) General date/long time: . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(M) Month:. . . . . . . . . . {0:M}" & vbCrLf & _
"(R) RFC1123:. . . . . . . . . {0:R}" & vbCrLf & _
"(s) Sortable: . . . . . . . . {0:s}" & vbCrLf & _
"(u) Universal sortable: . . . {0:u} (invariant)" & vbCrLf & _
"(U) Universal full date/time: {0:U}" & vbCrLf & _
"(Y) Year: . . . . . . . . . . {0:Y}" & vbCrLf, _
thisDate)
' Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers")
Console.WriteLine("(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)" & vbCrLf & _
"(D) Decimal number: . . . . . {0:D}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
Color.Green)
End Sub
End Class
'
'This code example produces the following results:
'
'Standard Numeric Format Specifiers
'(C) Currency: . . . . . . . . ($123.00)
'(D) Decimal:. . . . . . . . . -123
'(E) Scientific: . . . . . . . -1.234500E+002
'(F) Fixed point:. . . . . . . -123.45
'(G) General:. . . . . . . . . -123
' (default):. . . . . . . . -123 (default = 'G')
'(N) Number: . . . . . . . . . -123.00
'(P) Percent:. . . . . . . . . -12,345.00 %
'(R) Round-trip: . . . . . . . -123.45
'(X) Hexadecimal:. . . . . . . FFFFFF85
'
'Standard DateTime Format Specifiers
'(d) Short date: . . . . . . . 6/26/2004
'(D) Long date:. . . . . . . . Saturday, June 26, 2004
'(t) Short time: . . . . . . . 8:11 PM
'(T) Long time:. . . . . . . . 8:11:04 PM
'(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
'(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
'(g) General date/short time:. 6/26/2004 8:11 PM
'(G) General date/long time: . 6/26/2004 8:11:04 PM
' (default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
'(M) Month:. . . . . . . . . . June 26
'(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
'(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
'(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
'(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
'(Y) Year: . . . . . . . . . . June, 2004
'
'Standard Enumeration Format Specifiers
'(G) General:. . . . . . . . . Green
' (default):. . . . . . . . Green (default = 'G')
'(F) Flags:. . . . . . . . . . Green (flags or integer)
'(D) Decimal number: . . . . . 3
'(X) Hexadecimal:. . . . . . . 00000003
'
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
Este método usa la característica de formato compuesto de .net para convertir el valor de un objeto en su representación de texto e incrustar esa representación en una cadena.This method uses the composite formatting feature of .NET to convert the value of an object to its text representation and embed that representation in a string. La cadena resultante se escribe en el flujo de salida.The resulting string is written to the output stream.
El format parámetro se compone de cero o más ejecuciones de texto combinadas con cero o más marcadores de posición indizados, denominados elementos de formato, que corresponden a un objeto de la lista de parámetros de este método.The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. El proceso de formato reemplaza cada elemento de formato con la representación de texto del valor del objeto correspondiente.The formatting process replaces each format item with the text representation of the value of the corresponding object.
La sintaxis de un elemento de formato es { index[ , alignment] [ : FormatString] } , que especifica un índice obligatorio, la longitud opcional y la alineación del texto con formato, y una cadena opcional de caracteres especificadores de formato que rigen cómo se da formato al valor del objeto correspondiente.The syntax of a format item is {index[,alignment][:formatString]}, which specifies a mandatory index, the optional length and alignment of the formatted text, and an optional string of format specifier characters that govern how the value of the corresponding object is formatted.
.NET proporciona una gran compatibilidad con el formato, que se describe con más detalle en los siguientes temas de formato..NET provides extensive formatting support, which is described in greater detail in the following formatting topics.
Para obtener más información sobre la característica de formato compuesto compatible con métodos como Format , AppendFormat y algunas sobrecargas de WriteLine , vea formato compuesto.For more information about the composite formatting feature supported by methods such as Format, AppendFormat, and some overloads of WriteLine, see Composite Formatting.
Para obtener más información sobre los especificadores de formato numérico, vea cadenas de formato numérico estándar y cadenas de formato numérico personalizado.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Para obtener más información sobre los especificadores de formato de fecha y hora, vea cadenas con formato de fecha y hora estándar y cadenas con formato de fecha y hora personalizado.For more information about date and time format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Para obtener más información sobre los especificadores de formato de enumeración, vea cadenas de formato de enumeración.For more information about enumeration format specifiers, see Enumeration Format Strings.
Para obtener más información sobre el formato, vea aplicar formato a tipos.For more information about formatting, see Formatting Types.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Notas a los autores de las llamadas
El código de C++ no llama a este método.This method is not called by C++ code. El compilador de C++ resuelve las llamadas a System. Console. WriteLine que incluyen una cadena y una lista de cuatro o más parámetros de objeto como una llamada a WriteLine(String, Object, Object, Object, Object) .The C++ compiler resolves calls to System.Console.WriteLine that include a string and a list of four or more object parameters as a call to WriteLine(String, Object, Object, Object, Object). Resuelve las llamadas a System. Console. WriteLine que incluyen una cadena y una matriz de objetos como una llamada a WriteLine(String, Object) .It resolves calls to System.Console.WriteLine that include a string and an object array as a call to WriteLine(String, Object).
Consulte también
- Read()
- ReadLine()
- Write(String, Object)
- Aplicar formato a tipos en .NETFormatting Types in .NET
- Formatos compuestosComposite Formatting
Se aplica a
WriteLine(String, Object)
Escribe la representación de texto del objeto especificado, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
public:
static void WriteLine(System::String ^ format, System::Object ^ arg0);
public static void WriteLine (string format, object? arg0);
public static void WriteLine (string format, object arg0);
static member WriteLine : string * obj -> unit
Public Shared Sub WriteLine (format As String, arg0 As Object)
Parámetros
- format
- String
Cadena de formato compuesto.A composite format string.
- arg0
- Object
Objeto que se va a escribir con format.An object to write using format.
Excepciones
Error de E/S.An I/O error occurred.
format es null.format is null.
La especificación de formato de format no es válida.The format specification in format is invalid.
Ejemplos
En el ejemplo siguiente se llama al WriteLine(String, Object) método para mostrar cinco valores generados de forma aleatoria Boolean .The following example calls the WriteLine(String, Object) method to display five randomly generated Boolean values.
Random rnd = new Random();
// Generate five random Boolean values.
for (int ctr = 1; ctr <= 5; ctr++) {
Boolean bln = Convert.ToBoolean(rnd.Next(0, 2));
Console.WriteLine("True or False: {0}", bln);
}
// The example displays an output similar to the following:
// True or False: False
// True or False: True
// True or False: False
// True or False: False
// True or False: True
Module Example
Public Sub Main()
Dim rnd As New Random()
' Generate five random Boolean values.
For ctr As Integer = 1 To 5
Dim bool As Boolean = Convert.ToBoolean(rnd.Next(0, 2))
Console.WriteLine("True or False: {0}", bool)
Next
End Sub
End Module
' The example displays the following output:
' True or False: False
' True or False: True
' True or False: False
' True or False: False
' True or False: True
En el ejemplo siguiente se llama al WriteLine(String, Object) método para mostrar la fecha actual.The following example calls the WriteLine(String, Object) method to display the current date. Tenga en cuenta que en el elemento de formato del format argumento se usa la cadena de formato de fecha y hora estándar "D" para mostrar la fecha en el formato de fecha larga de la referencia cultural actual.Note that the format item in the format argument uses the "D" standard date and time format string to display the date in the long date format of the current culture.
using System;
public class Example
{
public static void Main()
{
Console.WriteLine("Today's date: {0:D}", DateTime.Now);
}
}
// The example displays output like the following:
// Today's date: Monday, April 1, 2019
Module Example
Public Sub Main()
Console.WriteLine("Today's date: {0:D}", DateTime.Now)
End Sub
End Module
' The example displays output like the following:
' Today's date: Friday, April 1, 2016
Comentarios
Este método usa la característica de formato compuesto de .net para convertir el valor de un objeto en su representación de texto e incrustar esa representación en una cadena.This method uses the composite formatting feature of .NET to convert the value of an object to its text representation and embed that representation in a string. La cadena resultante se escribe en el flujo de salida.The resulting string is written to the output stream.
El format parámetro se compone de cero o más ejecuciones de texto combinadas con cero o más marcadores de posición indizados, denominados elementos de formato, que corresponden a un objeto de la lista de parámetros de este método.The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. El proceso de formato reemplaza cada elemento de formato con la representación de texto del valor del objeto correspondiente.The formatting process replaces each format item with the text representation of the value of the corresponding object.
La sintaxis de un elemento de formato es { index[ , alignment] [ : FormatString] } , que especifica un índice obligatorio, la longitud opcional y la alineación del texto con formato, y una cadena opcional de caracteres especificadores de formato que rigen cómo se da formato al valor del objeto correspondiente.The syntax of a format item is {index[,alignment][:formatString]}, which specifies a mandatory index, the optional length and alignment of the formatted text, and an optional string of format specifier characters that govern how the value of the corresponding object is formatted.
.NET proporciona una gran compatibilidad con el formato, que se describe con más detalle en los siguientes temas de formato..NET provides extensive formatting support, which is described in greater detail in the following formatting topics.
Para obtener más información sobre la característica de formato compuesto compatible con métodos como Format , AppendFormat y algunas sobrecargas de WriteLine , vea formato compuesto.For more information about the composite formatting feature supported by methods such as Format, AppendFormat, and some overloads of WriteLine, see Composite Formatting.
Para obtener más información sobre los especificadores de formato numérico, vea cadenas de formato numérico estándar y cadenas de formato numérico personalizado.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Para obtener más información sobre los especificadores de formato de fecha y hora, vea cadenas con formato de fecha y hora estándar y cadenas con formato de fecha y hora personalizado.For more information about date and time format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Para obtener más información sobre los especificadores de formato de enumeración, vea cadenas de formato de enumeración.For more information about enumeration format specifiers, see Enumeration Format Strings.
Para obtener más información sobre el formato, vea aplicar formato a tipos.For more information about formatting, see Formatting Types.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
- Read()
- ReadLine()
- Write(String, Object)
- Aplicar formato a tipos en .NETFormatting Types in .NET
- Formatos compuestosComposite Formatting
Se aplica a
WriteLine(UInt64)
Importante
Esta API no es conforme a CLS.
Escribe la representación de texto del valor entero de 64 bits sin signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(System::UInt64 value);
[System.CLSCompliant(false)]
public static void WriteLine (ulong value);
[<System.CLSCompliant(false)>]
static member WriteLine : uint64 -> unit
Public Shared Sub WriteLine (value As ULong)
Parámetros
- value
- UInt64
Valor que se va a escribir.The value to write.
- Atributos
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
La representación de texto de value se genera mediante una llamada al UInt64.ToString método.The text representation of value is produced by calling the UInt64.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(UInt32)
Importante
Esta API no es conforme a CLS.
Escribe la representación de texto del valor entero de 32 bits sin signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(System::UInt32 value);
[System.CLSCompliant(false)]
public static void WriteLine (uint value);
[<System.CLSCompliant(false)>]
static member WriteLine : uint32 -> unit
Public Shared Sub WriteLine (value As UInteger)
Parámetros
- value
- UInt32
Valor que se va a escribir.The value to write.
- Atributos
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
La representación de texto de value se genera mediante una llamada al UInt32.ToString método.The text representation of value is produced by calling the UInt32.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Single)
Escribe la representación de texto del valor de punto flotante de precisión sencilla especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified single-precision floating-point value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(float value);
public static void WriteLine (float value);
static member WriteLine : single -> unit
Public Shared Sub WriteLine (value As Single)
Parámetros
- value
- Single
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
La representación de texto de value se genera mediante una llamada al Single.ToString método.The text representation of value is produced by calling the Single.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Decimal)
public:
static void WriteLine(System::Decimal value);
public static void WriteLine (decimal value);
static member WriteLine : decimal -> unit
Public Shared Sub WriteLine (value As Decimal)
Parámetros
- value
- Decimal
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
La representación de texto de value se genera mediante una llamada al Decimal.ToString método.The text representation of value is produced by calling the Decimal.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Int64)
Escribe la representación de texto del valor entero de 64 bits con signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 64-bit signed integer value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(long value);
public static void WriteLine (long value);
static member WriteLine : int64 -> unit
Public Shared Sub WriteLine (value As Long)
Parámetros
- value
- Int64
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
La representación de texto de value se genera mediante una llamada al Int64.ToString método.The text representation of value is produced by calling the Int64.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Int32)
Escribe la representación de texto del valor entero de 32 bits con signo especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified 32-bit signed integer value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(int value);
public static void WriteLine (int value);
static member WriteLine : int -> unit
Public Shared Sub WriteLine (value As Integer)
Parámetros
- value
- Int32
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
La representación de texto de value se genera mediante una llamada al Int32.ToString método.The text representation of value is produced by calling the Int32.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Double)
Escribe la representación de texto del valor de punto flotante de precisión doble especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified double-precision floating-point value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(double value);
public static void WriteLine (double value);
static member WriteLine : double -> unit
Public Shared Sub WriteLine (value As Double)
Parámetros
- value
- Double
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
La representación de texto de value se genera mediante una llamada al Double.ToString método.The text representation of value is produced by calling the Double.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Char[])
Escribe la matriz de caracteres Unicode especificada, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(cli::array <char> ^ buffer);
public static void WriteLine (char[]? buffer);
public static void WriteLine (char[] buffer);
static member WriteLine : char[] -> unit
Public Shared Sub WriteLine (buffer As Char())
Parámetros
- buffer
- Char[]
Matriz de caracteres Unicode.A Unicode character array.
Excepciones
Error de E/S.An I/O error occurred.
Comentarios
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Char)
Escribe el carácter Unicode especificado, seguido del terminador de línea actual, en el flujo de salida estándar.Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream.
public:
static void WriteLine(char value);
public static void WriteLine (char value);
static member WriteLine : char -> unit
Public Shared Sub WriteLine (value As Char)
Parámetros
- value
- Char
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(Boolean)
Escribe la representación de texto del valor booleano especificado, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified Boolean value, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(bool value);
public static void WriteLine (bool value);
static member WriteLine : bool -> unit
Public Shared Sub WriteLine (value As Boolean)
Parámetros
- value
- Boolean
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
En el ejemplo siguiente se generan diez enteros aleatorios y Console.WriteLine(Boolean) se usa el método para indicar si son pares.The following example generates ten random integers and uses the Console.WriteLine(Boolean) method to indicate whether they are even.
using namespace System;
void main()
{
// Assign 10 random integers to an array.
Random^ rnd = gcnew Random();
array<Int32>^ numbers = gcnew array<Int32>(10);
for (int ctr = 0; ctr <= numbers->GetUpperBound(0); ctr++)
numbers[ctr] = rnd->Next();
// Determine whether the numbers are even or odd.
for each (Int32 number in numbers) {
bool even = (number % 2 == 0);
Console::WriteLine("Is {0} even:", number);
Console::WriteLine(even);
Console::WriteLine();
}
}
// Assign 10 random integers to an array.
Random rnd = new Random();
int[] numbers = new int[10];
for (int ctr = 0; ctr <= numbers.GetUpperBound(0); ctr++)
numbers[ctr] = rnd.Next();
// Determine whether the numbers are even or odd.
foreach (var number in numbers) {
bool even = (number % 2 == 0);
Console.WriteLine("Is {0} even:", number);
Console.WriteLine(even);
Console.WriteLine();
}
Module Example
Public Sub Main()
' Assign 10 random integers to an array.
Dim rnd As New Random()
Dim numbers(9) As Integer
For ctr As Integer = 0 To numbers.GetUpperBound(0)
numbers(ctr) = rnd.Next
Next
' Determine whether the numbers are even or odd.
For Each number In numbers
Dim even As Boolean = (number mod 2 = 0)
Console.WriteLine("Is {0} even:", number)
Console.WriteLine(even)
Console.WriteLine()
Next
End Sub
End Module
Comentarios
La representación de texto de value se genera mediante una llamada al Boolean.ToString método.The text representation of value is produced by calling the Boolean.ToString method.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine()
Escribe el terminador de línea actual en el flujo de salida estándar.Writes the current line terminator to the standard output stream.
public:
static void WriteLine();
public static void WriteLine ();
static member WriteLine : unit -> unit
Public Shared Sub WriteLine ()
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
En el ejemplo se cambia el terminador de línea de su valor predeterminado de "\r\n" o vbCrLf a "\r\n\r\n" o vbCrLf + vbCrLf .The example changes the line terminator from its default value of "\r\n" or vbCrLf to "\r\n\r\n" or vbCrLf + vbCrLf. A continuación, llama a los WriteLine() WriteLine(String) métodos y para mostrar la salida en la consola.It then calls the WriteLine() and WriteLine(String) methods to display output to the console.
using namespace System;
void main()
{
array<String^>^ lines = gcnew array<String^> { "This is the first line.",
"This is the second line." };
// Output the lines using the default newline sequence.
Console::WriteLine("With the default new line characters:");
Console::WriteLine();
for each (String^ line in lines)
Console::WriteLine(line);
Console::WriteLine();
// Redefine the newline characters to double space.
Console::Out->NewLine = "\r\n\r\n";
// Output the lines using the new newline sequence.
Console::WriteLine("With redefined new line characters:");
Console::WriteLine();
for each (String^ line in lines)
Console::WriteLine(line);
}
// The example displays the following output:
// With the default new line characters:
//
// This is the first line.
// This is the second line.
//
// With redefined new line characters:
//
//
//
// This is the first line.
//
// This is the second line.
string[] lines = { "This is the first line.",
"This is the second line." };
// Output the lines using the default newline sequence.
Console.WriteLine("With the default new line characters:");
Console.WriteLine();
foreach (string line in lines)
Console.WriteLine(line);
Console.WriteLine();
// Redefine the newline characters to double space.
Console.Out.NewLine = "\r\n\r\n";
// Output the lines using the new newline sequence.
Console.WriteLine("With redefined new line characters:");
Console.WriteLine();
foreach (string line in lines)
Console.WriteLine(line);
// The example displays the following output:
// With the default new line characters:
//
// This is the first line.
// This is the second line.
//
// With redefined new line characters:
//
//
//
// This is the first line.
//
// This is the second line.
Module Example
Public Sub Main()
Dim lines() As String = { "This is the first line.", _
"This is the second line." }
' Output the lines using the default newline sequence.
Console.WriteLine("With the default new line characters:")
Console.WriteLine()
For Each line As String In lines
Console.WriteLine(line)
Next
Console.WriteLine()
' Redefine the newline characters to double space.
Console.Out.NewLine = vbCrLf + vbCrLf
' Output the lines using the new newline sequence.
Console.WriteLine("With redefined new line characters:")
Console.WriteLine()
For Each line As String In lines
Console.WriteLine(line)
Next
End Sub
End Module
' The example displays the following output:
' With the default new line characters:
'
' This is the first line.
' This is the second line.
'
' With redefined new line characters:
'
'
'
' This is the first line.
'
' This is the second line.
Comentarios
El terminador de línea predeterminado es una cadena cuyo valor es un retorno de carro seguido de un salto de línea ("\r\n" en C#, o vbCrLf en Visual Basic).The default line terminator is a string whose value is a carriage return followed by a line feed ("\r\n" in C#, or vbCrLf in Visual Basic). Puede cambiar el terminador de línea estableciendo la TextWriter.NewLine propiedad de la Out propiedad en otra cadena.You can change the line terminator by setting the TextWriter.NewLine property of the Out property to another string. En este ejemplo se ilustra.The example provides an illustration.
Consulte también
Se aplica a
WriteLine(String, Object, Object, Object)
Escribe la representación de texto de los objetos especificados, seguida del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
public:
static void WriteLine(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static void WriteLine (string format, object? arg0, object? arg1, object? arg2);
public static void WriteLine (string format, object arg0, object arg1, object arg2);
static member WriteLine : string * obj * obj * obj -> unit
Public Shared Sub WriteLine (format As String, arg0 As Object, arg1 As Object, arg2 As Object)
Parámetros
- format
- String
Cadena de formato compuesto.A composite format string.
- arg0
- Object
Primer objeto que se va a escribir con format.The first object to write using format.
- arg1
- Object
Segundo objeto que se va a escribir con format.The second object to write using format.
- arg2
- Object
Tercer objeto que se va a escribir con format.The third object to write using format.
Excepciones
Error de E/S.An I/O error occurred.
format es null.format is null.
La especificación de formato de format no es válida.The format specification in format is invalid.
Ejemplos
En el ejemplo siguiente se muestran los especificadores de formato estándar para números, fechas y enumeraciones.The following example demonstrates the standard formatting specifiers for numbers, dates, and enumerations.
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using namespace System;
public enum class Color {Yellow = 1, Blue, Green};
int main()
{
DateTime thisDate = DateTime::Now;
Console::Clear();
// Format a negative integer or floating-point number in various ways.
Console::WriteLine("Standard Numeric Format Specifiers");
Console::WriteLine(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
// Format the current date in various ways.
Console::WriteLine("Standard DateTime Format Specifiers");
Console::WriteLine(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal full date/time: {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
// Format a Color enumeration value in various ways.
Console::WriteLine("Standard Enumeration Format Specifiers");
Console::WriteLine(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color::Green);
};
/*
This code example produces the following results:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using System;
class Sample
{
enum Color {Yellow = 1, Blue, Green};
static DateTime thisDate = DateTime.Now;
public static void Main()
{
Console.Clear();
// Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers");
Console.WriteLine(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);
// Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers");
Console.WriteLine(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal full date/time: {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
// Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers");
Console.WriteLine(
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n" +
"(D) Decimal number: . . . . . {0:D}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
Color.Green);
}
}
/*
This code example produces the following results:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
(default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
(default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/
' This code example demonstrates the Console.WriteLine() method.
' Formatting for this example uses the "en-US" culture.
Class Sample
Public Enum Color
Yellow = 1
Blue = 2
Green = 3
End Enum 'Color
Private Shared thisDate As DateTime = DateTime.Now
Public Shared Sub Main()
Console.Clear()
' Format a negative integer or floating-point number in various ways.
Console.WriteLine("Standard Numeric Format Specifiers")
Console.WriteLine("(C) Currency: . . . . . . . . {0:C}" & vbCrLf & _
"(D) Decimal:. . . . . . . . . {0:D}" & vbCrLf & _
"(E) Scientific: . . . . . . . {1:E}" & vbCrLf & _
"(F) Fixed point:. . . . . . . {1:F}" & vbCrLf & _
"(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(N) Number: . . . . . . . . . {0:N}" & vbCrLf & _
"(P) Percent:. . . . . . . . . {1:P}" & vbCrLf & _
"(R) Round-trip: . . . . . . . {1:R}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
- 123, - 123.45F)
' Format the current date in various ways.
Console.WriteLine("Standard DateTime Format Specifiers")
Console.WriteLine("(d) Short date: . . . . . . . {0:d}" & vbCrLf & _
"(D) Long date:. . . . . . . . {0:D}" & vbCrLf & _
"(t) Short time: . . . . . . . {0:t}" & vbCrLf & _
"(T) Long time:. . . . . . . . {0:T}" & vbCrLf & _
"(f) Full date/short time: . . {0:f}" & vbCrLf & _
"(F) Full date/long time:. . . {0:F}" & vbCrLf & _
"(g) General date/short time:. {0:g}" & vbCrLf & _
"(G) General date/long time: . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(M) Month:. . . . . . . . . . {0:M}" & vbCrLf & _
"(R) RFC1123:. . . . . . . . . {0:R}" & vbCrLf & _
"(s) Sortable: . . . . . . . . {0:s}" & vbCrLf & _
"(u) Universal sortable: . . . {0:u} (invariant)" & vbCrLf & _
"(U) Universal full date/time: {0:U}" & vbCrLf & _
"(Y) Year: . . . . . . . . . . {0:Y}" & vbCrLf, _
thisDate)
' Format a Color enumeration value in various ways.
Console.WriteLine("Standard Enumeration Format Specifiers")
Console.WriteLine("(G) General:. . . . . . . . . {0:G}" & vbCrLf & _
" (default):. . . . . . . . {0} (default = 'G')" & vbCrLf & _
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer)" & vbCrLf & _
"(D) Decimal number: . . . . . {0:D}" & vbCrLf & _
"(X) Hexadecimal:. . . . . . . {0:X}" & vbCrLf, _
Color.Green)
End Sub
End Class
'
'This code example produces the following results:
'
'Standard Numeric Format Specifiers
'(C) Currency: . . . . . . . . ($123.00)
'(D) Decimal:. . . . . . . . . -123
'(E) Scientific: . . . . . . . -1.234500E+002
'(F) Fixed point:. . . . . . . -123.45
'(G) General:. . . . . . . . . -123
' (default):. . . . . . . . -123 (default = 'G')
'(N) Number: . . . . . . . . . -123.00
'(P) Percent:. . . . . . . . . -12,345.00 %
'(R) Round-trip: . . . . . . . -123.45
'(X) Hexadecimal:. . . . . . . FFFFFF85
'
'Standard DateTime Format Specifiers
'(d) Short date: . . . . . . . 6/26/2004
'(D) Long date:. . . . . . . . Saturday, June 26, 2004
'(t) Short time: . . . . . . . 8:11 PM
'(T) Long time:. . . . . . . . 8:11:04 PM
'(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
'(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
'(g) General date/short time:. 6/26/2004 8:11 PM
'(G) General date/long time: . 6/26/2004 8:11:04 PM
' (default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
'(M) Month:. . . . . . . . . . June 26
'(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
'(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
'(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
'(U) Universal full date/time: Sunday, June 27, 2004 3:11:04 AM
'(Y) Year: . . . . . . . . . . June, 2004
'
'Standard Enumeration Format Specifiers
'(G) General:. . . . . . . . . Green
' (default):. . . . . . . . Green (default = 'G')
'(F) Flags:. . . . . . . . . . Green (flags or integer)
'(D) Decimal number: . . . . . 3
'(X) Hexadecimal:. . . . . . . 00000003
'
El ejemplo siguiente es una calculadora de propinas que calcula una sugerencia del 18% y usa el WriteLine método para mostrar la cantidad de cargo original, la cantidad de la propina y la cantidad total.The following example is a tip calculator that calculates an 18% tip and uses the WriteLine method to display the amount of the original charge, the amount of the tip, and the total amount. El ejemplo es una aplicación de consola que requiere que el usuario proporcione la cantidad de cargo original como parámetro de línea de comandos.The example is a console application that requires the user to supply the amount of the original charge as a command-line parameter.
using System;
public class TipCalculator
{
private const double tipRate = 0.18;
public static void Main(string[] args)
{
double billTotal;
if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
}
double tip = billTotal * tipRate;
Console.WriteLine();
Console.WriteLine($"Bill total:\t{billTotal,8:c}");
Console.WriteLine($"Tip total/rate:\t{tip,8:c} ({tipRate:p1})");
Console.WriteLine(("").PadRight(24, '-'));
Console.WriteLine($"Grand total:\t{billTotal + tip,8:c}");
}
}
/*
>tipcalc 52.23
Bill total: $52.23
Tip total/rate: $9.40 (18.0 %)
------------------------
Grand total: $61.63
*/
Public Module TipCalculator
Private Const tipRate As Double = 0.18
Public Sub Main(args As String())
Dim billTotal As Double
If (args.Length = 0) OrElse (Not Double.TryParse(args(0), billTotal)) Then
Console.WriteLine("usage: TIPCALC total")
Return
End If
Dim tip As Double = billTotal * tipRate
Console.WriteLine()
Console.WriteLine($"Bill total:{vbTab}{billTotal,8:c}")
Console.WriteLine($"Tip total/rate:{vbTab}{tip,8:c} ({tipRate:p1})")
Console.WriteLine("".PadRight(24, "-"c))
Console.WriteLine($"Grand total:{vbTab}{billTotal + tip,8:c}")
End Sub
End Module
'Example Output:
'---------------
' >tipcalc 52.23
'
' Bill total: $52.23
' Tip total/rate: $9.40 (18.0 %)
' ------------------------
' Grand total: $61.63
Comentarios
Este método usa la característica de formato compuesto de .net para convertir el valor de un objeto en su representación de texto e incrustar esa representación en una cadena.This method uses the composite formatting feature of .NET to convert the value of an object to its text representation and embed that representation in a string. La cadena resultante se escribe en el flujo de salida.The resulting string is written to the output stream.
El format parámetro se compone de cero o más ejecuciones de texto combinadas con cero o más marcadores de posición indizados, denominados elementos de formato, que corresponden a un objeto de la lista de parámetros de este método.The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. El proceso de formato reemplaza cada elemento de formato con la representación de texto del valor del objeto correspondiente.The formatting process replaces each format item with the text representation of the value of the corresponding object.
La sintaxis de un elemento de formato es { index[ , alignment] [ : FormatString] } , que especifica un índice obligatorio, la longitud opcional y la alineación del texto con formato, y una cadena opcional de caracteres especificadores de formato que rigen cómo se da formato al valor del objeto correspondiente.The syntax of a format item is {index[,alignment][:formatString]}, which specifies a mandatory index, the optional length and alignment of the formatted text, and an optional string of format specifier characters that govern how the value of the corresponding object is formatted.
.NET proporciona una gran compatibilidad con el formato, que se describe con más detalle en los siguientes temas de formato..NET provides extensive formatting support, which is described in greater detail in the following formatting topics.
Para obtener más información sobre la característica de formato compuesto compatible con métodos como Format , AppendFormat y algunas sobrecargas de WriteLine , vea formato compuesto.For more information about the composite formatting feature supported by methods such as Format, AppendFormat, and some overloads of WriteLine, see Composite Formatting.
Para obtener más información sobre los especificadores de formato numérico, vea cadenas de formato numérico estándar y cadenas de formato numérico personalizado.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Para obtener más información sobre los especificadores de formato de fecha y hora, vea cadenas con formato de fecha y hora estándar y cadenas con formato de fecha y hora personalizado.For more information about date and time format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Para obtener más información sobre los especificadores de formato de enumeración, vea cadenas de formato de enumeración.For more information about enumeration format specifiers, see Enumeration Format Strings.
Para obtener más información sobre el formato, vea aplicar formato a tipos.For more information about formatting, see Formatting Types.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
- Read()
- ReadLine()
- Write(String, Object)
- Aplicar formato a tipos en .NETFormatting Types in .NET
- Formatos compuestosComposite Formatting
Se aplica a
WriteLine(Object)
Escribe la representación de texto del objeto especificado, seguida del terminador de línea actual, en el flujo de salida estándar.Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.
public:
static void WriteLine(System::Object ^ value);
public static void WriteLine (object? value);
public static void WriteLine (object value);
static member WriteLine : obj -> unit
Public Shared Sub WriteLine (value As Object)
Parámetros
- value
- Object
Valor que se va a escribir.The value to write.
Excepciones
Error de E/S.An I/O error occurred.
Ejemplos
En el ejemplo siguiente se usa el WriteLine(Object) método para mostrar cada valor de una matriz de objetos en la consola.The following example uses the WriteLine(Object) method to display each value in an object array to the console.
using namespace System;
void main()
{
array<Object^>^ values = { true, 12.632, 17908, "stringValue",
'a', (Decimal) 16907.32 };
for each (Object^ value in values)
Console::WriteLine(value);
}
// The example displays the following output:
// True
// 12.632
// 17908
// stringValue
// a
// 16907.32
Object[] values = { true, 12.632, 17908, "stringValue",
'a', 16907.32m };
foreach (var value in values)
Console.WriteLine(value);
// The example displays the following output:
// True
// 12.632
// 17908
// stringValue
// a
// 16907.32
Module Example
Public Sub Main()
Dim values() As Object = { True, 12.632, 17908, "stringValue",
"a"c, 16907.32d }
For Each value In values
Console.WriteLine(value)
Next
End Sub
End Module
' The example displays the following output:
' True
' 12.632
' 17908
' stringValue
' a
' 16907.32
Comentarios
Si value es null, sólo se escribe el terminador de línea.If value is null, only the line terminator is written. De lo contrario, ToString se llama al método de value para generar su representación de cadena y la cadena resultante se escribe en el flujo de salida estándar.Otherwise, the ToString method of value is called to produce its string representation, and the resulting string is written to the standard output stream.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Consulte también
Se aplica a
WriteLine(String, Object, Object, Object, Object)
Importante
Esta API no es conforme a CLS.
Escribe la representación de texto de los objetos especificados y la lista de parámetros de longitud variable, seguidas del terminador de línea actual, en el flujo de salida estándar usando la información de formato especificada.Writes the text representation of the specified objects and variable-length parameter list, followed by the current line terminator, to the standard output stream using the specified format information.
public:
static void WriteLine(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2, System::Object ^ arg3);
[System.CLSCompliant(false)]
public static void WriteLine (string format, object arg0, object arg1, object arg2, object arg3);
[<System.CLSCompliant(false)>]
static member WriteLine : string * obj * obj * obj * obj -> unit
Public Shared Sub WriteLine (format As String, arg0 As Object, arg1 As Object, arg2 As Object, arg3 As Object)
Parámetros
- format
- String
Cadena de formato compuesto.A composite format string.
- arg0
- Object
Primer objeto que se va a escribir con format.The first object to write using format.
- arg1
- Object
Segundo objeto que se va a escribir con format.The second object to write using format.
- arg2
- Object
Tercer objeto que se va a escribir con format.The third object to write using format.
- arg3
- Object
Cuarto objeto que se va a escribir con format.The fourth object to write using format.
- Atributos
Excepciones
Error de E/S.An I/O error occurred.
format es null.format is null.
La especificación de formato de format no es válida.The format specification in format is invalid.
Ejemplos
En el ejemplo siguiente se muestra el uso de argumentos de variable con el WriteLine(String, Object, Object, Object, Object) método.The following example illustrates the use of variable arguments with the WriteLine(String, Object, Object, Object, Object) method. Se llama al método con una cadena de formato compuesto y cinco elementos de formato.The method is called with a composite format string and five format items.
using namespace System;
int CountLetters(String^ value);
int CountWhitespace(String^ value);
void main()
{
String^ value = "This is a test string.";
Console::WriteLine("The string '{0}' consists of:" +
"{4}{1} characters{4}{2} letters{4}" +
"{3} white-space characters",
value, value->Length, CountLetters(value),
CountWhitespace(value), Environment::NewLine);
}
int CountLetters(String^ value)
{
int nLetters = 0;
for each (Char ch in value) {
if (Char::IsLetter(ch))
nLetters++;
}
return nLetters;
}
int CountWhitespace(String^ value)
{
int nWhitespace = 0;
for each (Char ch in value) {
if (Char::IsWhiteSpace(ch))
nWhitespace++;
}
return nWhitespace;
}
// The example displays the following output:
// The string 'This is a test string.' consists of:
// 22 characters
// 17 letters
// 4 white-space characters
Comentarios
Nota
Esta API no es conforme a CLS.This API is not CLS-compliant. La alternativa conforme a CLS es Console.WriteLine(String, Object[]).The CLS-compliant alternative is Console.WriteLine(String, Object[]). Los compiladores de C# y Visual Basic resuelven automáticamente una llamada a este método como una llamada a Console.WriteLine(String, Object[]) .The C# and Visual Basic compilers automatically resolve a call to this method as a call to Console.WriteLine(String, Object[]).
Este método usa la característica de formato compuesto de .net para convertir el valor de un objeto en su representación de texto e incrustar esa representación en una cadena.This method uses the composite formatting feature of .NET to convert the value of an object to its text representation and embed that representation in a string. La cadena resultante se escribe en el flujo de salida.The resulting string is written to the output stream.
El format parámetro se compone de cero o más ejecuciones de texto combinadas con cero o más marcadores de posición indizados, denominados elementos de formato, que corresponden a un objeto de la lista de parámetros de este método.The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. El proceso de formato reemplaza cada elemento de formato con la representación de texto del valor del objeto correspondiente.The formatting process replaces each format item with the text representation of the value of the corresponding object.
La sintaxis de un elemento de formato es { index[ , alignment] [ : FormatString] } , que especifica un índice obligatorio, la longitud opcional y la alineación del texto con formato, y una cadena opcional de caracteres especificadores de formato que rigen cómo se da formato al valor del objeto correspondiente.The syntax of a format item is {index[,alignment][:formatString]}, which specifies a mandatory index, the optional length and alignment of the formatted text, and an optional string of format specifier characters that govern how the value of the corresponding object is formatted.
.NET proporciona una gran compatibilidad con el formato, que se describe con más detalle en los siguientes temas de formato..NET provides extensive formatting support, which is described in greater detail in the following formatting topics.
Para obtener más información sobre la característica de formato compuesto compatible con métodos como Format , AppendFormat y algunas sobrecargas de WriteLine , vea formato compuesto.For more information about the composite formatting feature supported by methods such as Format, AppendFormat, and some overloads of WriteLine, see Composite Formatting.
Para obtener más información sobre los especificadores de formato numérico, vea cadenas de formato numérico estándar y cadenas de formato numérico personalizado.For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Para obtener más información sobre los especificadores de formato de fecha y hora, vea cadenas con formato de fecha y hora estándar y cadenas con formato de fecha y hora personalizado.For more information about date and time format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Para obtener más información sobre los especificadores de formato de enumeración, vea cadenas de formato de enumeración.For more information about enumeration format specifiers, see Enumeration Format Strings.
Para obtener más información sobre el formato, vea aplicar formato a tipos.For more information about formatting, see Formatting Types.
Para obtener más información sobre el terminador de línea, vea la sección Comentarios del WriteLine método que no toma ningún parámetro.For more information about the line terminator, see the Remarks section of the WriteLine method that takes no parameters.
Notas a los autores de las llamadas
Este método se marca con la vararg palabra clave, lo que significa que admite un número variable de parámetros.This method is marked with the vararg keyword, which means that it supports a variable number of parameters. Se puede llamar al método desde Visual C++, pero no se puede llamar desde el código de C# o Visual Basic.The method can be called from Visual C++, but it cannot be called from C# or Visual Basic code. Los compiladores de C# y Visual Basic resuelven las llamadas a WriteLine(String, Object, Object, Object, Object) como llamadas a WriteLine(String, Object[]) .The C# and Visual Basic compilers resolve calls to WriteLine(String, Object, Object, Object, Object) as calls to WriteLine(String, Object[]).
Consulte también
- Read()
- ReadLine()
- Write(String, Object)
- Aplicar formato a tipos en .NETFormatting Types in .NET
- Formatos compuestosComposite Formatting