Интерфейс ISpanFormattable
Метод ISpanFormattable.TryFormat
пишет в Span<char> и
возвращает bool. Параметр
charsWritten - сколько символов
записано. Обычно реализуют вместе с
IFormattable.
Шаблон с объектом -
string.Format.
Синтаксис
bool ok = formattable.TryFormat(
destination, out int charsWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider);
Пример
Давайте запишем текст в
stackalloc буфер:
using System;
using System.Globalization;
class Box : IFormattable, ISpanFormattable
{
public string ToString(string? format, IFormatProvider? provider)
=> "abcde";
public bool TryFormat(
Span<char> destination,
out int charsWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider)
{
ReadOnlySpan<char> text = "abcde";
if (destination.Length < text.Length)
{
charsWritten = 0;
return false;
}
text.CopyTo(destination);
charsWritten = text.Length;
return true;
}
}
class Program
{
static void Main()
{
var box = new Box();
Span<char> buffer = stackalloc char[8];
box.TryFormat(buffer, out int res, "G", CultureInfo.InvariantCulture);
Console.WriteLine(res);
Console.WriteLine(new string(buffer.Slice(0, res)));
}
}
Результат выполнения кода:
5
"abcde"
Пример
Давайте проверим успешную запись через
bool:
using System;
using System.Globalization;
class Box : IFormattable, ISpanFormattable
{
public string ToString(string? format, IFormatProvider? provider)
=> "abcde";
public bool TryFormat(
Span<char> destination,
out int charsWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider)
{
ReadOnlySpan<char> text = "abcde";
if (destination.Length < text.Length)
{
charsWritten = 0;
return false;
}
text.CopyTo(destination);
charsWritten = text.Length;
return true;
}
}
class Program
{
static void Main()
{
var box = new Box();
Span<char> buffer = stackalloc char[8];
bool res = box.TryFormat(
buffer, out _, "G", CultureInfo.InvariantCulture);
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Пример
Давайте дадим слишком короткий буфер:
using System;
using System.Globalization;
class Box : IFormattable, ISpanFormattable
{
public string ToString(string? format, IFormatProvider? provider)
=> "abcde";
public bool TryFormat(
Span<char> destination,
out int charsWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider)
{
ReadOnlySpan<char> text = "abcde";
if (destination.Length < text.Length)
{
charsWritten = 0;
return false;
}
text.CopyTo(destination);
charsWritten = text.Length;
return true;
}
}
class Program
{
static void Main()
{
var box = new Box();
Span<char> buffer = stackalloc char[3];
bool ok = box.TryFormat(
buffer, out int res, "G", CultureInfo.InvariantCulture);
Console.WriteLine(ok);
Console.WriteLine(res);
}
}
Результат выполнения кода:
False
0
Смотрите также
-
IFormattable,
формат в строку -
Составной формат,
сборка текста с объектом -
DateTime.ToString,
тип с встроенным форматом -
TimeSpan.ToString,
интервал с форматом