Proporciona funcionalidad para dar formato al valor de un objeto en una representación de cadena.
Espacio de nombres: System
Ensamblado: mscorlib (en mscorlib.dll)
Visual Basic (Declaración)
<ComVisibleAttribute(True)> _
Public Interface IFormattable
Dim instance As IFormattable
[ComVisibleAttribute(true)]
public interface IFormattable
[ComVisibleAttribute(true)]
public interface class IFormattable
/** @attribute ComVisibleAttribute(true) */
public interface IFormattable
ComVisibleAttribute(true)
public interface IFormattable
Los tipos de datos base implementan IFormattable.
Un formato describe la apariencia de un objeto cuando se convierte en una cadena. Puede ser estándar o personalizado. Un formato estándar adopta la forma Axx, donde A es un carácter alfabético denominado especificador de formato y xx es un entero no negativo denominado especificador de precisión. El especificador de formato controla el tipo de formato que se aplica al valor que se va a representar en forma de cadena. El especificador de precisión controla el número de dígitos significativos o posiciones decimales de la cadena, si procede.
Cuando un formato incluye símbolos que varían en función de la referencia cultural, como el símbolo de moneda representado por los formatos "C" y "c", un objeto de formato proporciona los caracteres reales que se utilizan en la representación de cadena. Un método puede incluir un parámetro para pasar un objeto IFormatProvider que proporciona un objeto de formato, o el método puede utilizar el objeto de formato predeterminado, que contiene las definiciones de símbolo para el subproceso actual. El subproceso actual utiliza normalmente el mismo conjunto de símbolos que se utilizan de forma predeterminada en todo el sistema.
Notas para los implementadores
Las clases que requieren un control sobre el formato de cadenas mayor que el que proporciona Object.ToString deben implementar IFormattable, cuyo método ToString utiliza la propiedad CurrentCulture del subproceso actual.
Una clase que implementa IFormattable debe admitir el código de formato "G" (general). Además del código "G", la clase puede definir la lista de códigos de formato que admite.
Para obtener más información sobre formato y códigos de formato, vea Información general sobre formatos.
En el siguiente ejemplo se muestra cómo definir un tipo que implementa la interfaz IFormattable. En el ejemplo se muestra también cómo llamar al método ToString de la interfaz IFormattable.
using System;
class Point : IFormattable
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override String ToString() { return ToString(null, null); }
public String ToString(String format, IFormatProvider fp)
{
// If no format is passed, display like this: (x, y).
if (format == null) return String.Format("({0}, {1})", x, y);
// For "x" formatting, return just the x value as a string
if (format == "x") return x.ToString();
// For "y" formatting, return just the y value as a string
if (format == "y") return y.ToString();
// For any unrecognized format, throw an exception.
throw new FormatException(String.Format("Invalid format string: '{0}'.", format));
}
}
public sealed class App
{
static void Main()
{
// Create the object.
Point p = new Point(5, 98);
// Test ToString with no formatting.
Console.WriteLine("This is my point: " + p.ToString());
// Use custom formatting style "x"
Console.WriteLine("The point's x value is {0:x}", p);
// Use custom formatting style "y"
Console.WriteLine("The point's y value is {0:y}", p);
try
{
// Use an invalid format; FormatException should be thrown here.
Console.WriteLine("Invalid way to format a point: {0:XYZ}", p);
}
catch (FormatException e)
{
Console.WriteLine("The last line could not be displayed: {0}", e.Message);
}
}
}
// This code produces the following output.
//
// This is my point: (5, 98)
// The point's x value is 5
// The point's y value is 98
// The last line could not be displayed: Invalid format string: 'XYZ'.
using namespace System;
public value struct Point : IFormattable
{
private:
int x;
private:
int y;
public:
property int X
{
int get()
{
return x;
}
void set(int value)
{
x = value;
}
}
public:
property int Y
{
int get()
{
return y;
}
void set(int value)
{
y = value;
}
}
public:
Point(int x, int y)
{
this->x = x;
this->y = y;
}
public:
virtual String^ ToString() override
{
return ToString(nullptr, nullptr);
}
public:
virtual String^ ToString(String^ format, IFormatProvider^ formatProvider)
{
// If no format is passed, display like this: (x, y).
if (format == nullptr)
{
return String::Format("({0}, {1})", x, y);
}
// For "x" formatting, return just the x value as a string
if (format == "x")
{
return x.ToString();
}
// For "y" formatting, return just the y value as a string
if (format == "y")
{
return y.ToString();
}
// For any unrecognized format, throw an exception.
throw gcnew FormatException(String::Format(
"Invalid format string: '{0}'.", format));
}
};
int main()
{
// Create the object.
Point p = Point(5, 98);
// Test ToString with no formatting.
Console::WriteLine("This is my point: " + p.ToString());
// Use custom formatting style "x"
Console::WriteLine("The point's x value is {0:x}", p);
// Use custom formatting style "y"
Console::WriteLine("The point's y value is {0:y}", p);
try
{
// Use an invalid format;
// FormatException should be thrown here.
Console::WriteLine(
"Invalid way to format a point: {0:XYZ}", p);
}
catch (FormatException^ e)
{
Console::WriteLine(
"The last line could not be displayed: {0}",
e->Message);
}
}
// This code produces the following output.
//
// This is my point: (5, 98)
// The point's x value is 5
// The point's y value is 98
// The last line could not be displayed: Invalid format string: 'XYZ'.
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition
.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.
.NET Framework
Compatible con: 2.0, 1.1, 1.0
.NET Compact Framework
Compatible con: 2.0, 1.0