我正在把VB转换成c#。这条语句的语法有问题:
if ((searchResult.Properties["user"].Count > 0))
{
profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}
然后我看到以下错误:
参数1:不能将'object'转换为'byte[]'
匹配的最佳重载方法
'System.Text.Encoding.GetString(byte[])'有一些无效的参数
我试图根据这篇文章修复代码,但仍然没有成功
string User = Encoding.UTF8.GetString("user", 0);
有什么建议吗?
基于阿里的回答,我会推荐一个扩展方法,允许你有选择地传入你想使用的编码:
using System.Text;
public static class StringExtensions
{
/// <summary>
/// Creates a byte array from the string, using the
/// System.Text.Encoding.Default encoding unless another is specified.
/// </summary>
public static byte[] ToByteArray(this string str, Encoding encoding = Encoding.Default)
{
return encoding.GetBytes(str);
}
}
然后像下面这样使用它:
string foo = "bla bla";
// default encoding
byte[] default = foo.ToByteArray();
// custom encoding
byte[] unicode = foo.ToByteArray(Encoding.Unicode);
您可以使用MemoryMarshal API来执行非常快速和有效的转换。字符串将隐式强制转换为ReadOnlySpan<字节>,作为MemoryMarshal。强制转换接受Span<byte>或ReadOnlySpan<byte>作为输入参数。
public static class StringExtensions
{
public static byte[] ToByteArray(this string s) => s.ToByteSpan().ToArray(); // heap allocation, use only when you cannot operate on spans
public static ReadOnlySpan<byte> ToByteSpan(this string s) => MemoryMarshal.Cast<char, byte>(s);
}
下面的基准测试显示了差异:
Input: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,"
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|----------------------------- |-----------:|----------:|----------:|-------:|------:|------:|----------:|
| UsingEncodingUnicodeGetBytes | 160.042 ns | 3.2864 ns | 6.4099 ns | 0.0780 | - | - | 328 B |
| UsingMemoryMarshalAndToArray | 31.977 ns | 0.7177 ns | 1.5753 ns | 0.0781 | - | - | 328 B |
| UsingMemoryMarshal | 1.027 ns | 0.0565 ns | 0.1630 ns | - | - | - | - |
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}