我想使用一些自定義格式引數將格式byte[]和位元組轉換為字串。ReadOnlySpan<byte>說,喜歡S。Base64為此,長度始終固定為某個已知常數。
我想使用https://devblogs.microsoft.com/dotnet/string-interpolation-in-c-10-and-net-6/中所述的現代 C# 10 和 .NET 6 字串格式化功能。內置型別實作ISpanFormattable,所以我想在這里帶來新的格式化引數,但是使用編譯器處理程式降低模式??。
我從該帖子中獲取了一些代碼,并在嵌入的代碼中對其進行了一些修改,如下所示。它也在https://dotnetfiddle.net/svyQKD。
從代碼中可以看出,我得到了成功的直接方法呼叫byte[],但沒有成功ReadOnlySpan<byte>。
有誰知道如何做到這一點?
我懷疑我需要InterpolatedStringHandler。但如果是這樣的話,那么看起來我不知道如何實作一個。所有提示和代碼技巧都可能會有所幫助。我已經被困了一段時間了,現在已經到凌晨了。:)
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
public class Program
{
public sealed class ExampleCustomFormatter: IFormatProvider, ICustomFormatter
{
public object? GetFormat(Type? formatType) => formatType == typeof(ICustomFormatter) ? this : null;
public string Format(string? format, object? arg, IFormatProvider? formatProvider) => format == "S" && arg is byte[] i ? Convert.ToBase64String(i) : arg is IFormattable formattable ? formattable.ToString(format, formatProvider) : arg?.ToString() ?? string.Empty;
}
public static class StringExtensions
{
public static string FormatString(byte[] buffer) => string.Create(new ExampleCustomFormatter(), stackalloc char[64], $"{buffer:S}");
// How to make this work? Maybe needs to have TryWrite
// public static string FormatString2(ReadOnlySpan<byte> buffer) => string.Create(new ExampleCustomFormatter(), stackalloc char[64], $"{buffer:S}");
}
[InterpolatedStringHandler]
public ref struct BinaryMessageInterpolatedStringHandler
{
private readonly DefaultInterpolatedStringHandler handler;
public BinaryMessageInterpolatedStringHandler(int literalLength, int formattedCount, bool predicate, out bool handlerIsValid)
{
handler = default;
if(predicate)
{
handlerIsValid = false;
return;
}
handlerIsValid = true;
handler = new DefaultInterpolatedStringHandler(literalLength, formattedCount);
}
public void AppendLiteral(string s) => handler.AppendLiteral(s);
public void AppendFormatted<T>(T t) => handler.AppendFormatted(t);
public override string ToString() => handler.ToStringAndClear();
}
public static void Main()
{
byte[] test1 = new byte[1] { 0x55 };
ReadOnlySpan<byte> test2 = new byte[1] { 0x55 };
// How to make this work? Now it prints "System.Byte[]".
Console.WriteLine($"{test1:S}");
// This works.
Console.WriteLine(StringExtensions.FormatString(test1));
// How to make this work? This does not compile. (Yes, signature problem. How to define it?).
// Console.WriteLine($"{test2:S}");
// How to make this work? This does not compile. (Yes, signature problem. How to define it?).
// Console.WriteLine(StringExtensions.FormatString(test2));
}
}
uj5u.com熱心網友回復:
您可以使用擴展方法:
using System.Text;
byte[] test1 = new byte[2] { 0x55, 0x34 };
ReadOnlySpan<byte> test2 = new byte[2] { 0x55, 0x34 };
// How to make this work? Now it prints "System.Byte[]".
Console.WriteLine($"{test1.MyFormat()}");
Console.WriteLine($"{test2.MyFormat()}");
public static class MyExtensionMethods
{
public static string MyFormat(this byte[] value)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in value)
{
sb.Append(b).Append(" ");
}
return sb.ToString();
}
public static string MyFormat(this ReadOnlySpan<byte> value)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in value)
{
sb.Append(b).Append(" ");
}
return sb.ToString();
}
}
結果:
85 52
85 52
您也可以嘗試:
public static class MyExtensionMethods
{
public static string MyFormat(this byte[] value) => Encoding.Unicode.GetString(value);
public static string MyFormat(this ReadOnlySpan<byte> value) => Encoding.Unicode.GetString(value);
}
uj5u.com熱心網友回復:
如果你真的想使用這樣的方法,你需要重寫ToString()類的方法Byte[]。
但是您不能在非常類上覆寫該方法Byte[]。您需要繼承該類Byte[]并覆寫ToString()派生的方法。
然后,您必須用Byte[]派生類替換所有物件,這不是一個好主意。
因此,這種方式沒有適合您的解決方案:
// How to make this work? Now it prints "System.Byte[]".
Console.WriteLine($"{test1:S}");
您可以做的最好的事情是創建一個“外部”方法來格式化Byte[]并按照您的方式進行格式化。
*同樣適用于ReadOnlySpan<byte>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/455889.html
