我正在把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);
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);
}
如果的结果,'searchResult.;属性["user"][0]',是一个字符串:
if ( ( searchResult.Properties [ "user" ].Count > 0 ) ) {
profile.User = System.Text.Encoding.UTF8.GetString ( searchResult.Properties [ "user" ] [ 0 ].ToCharArray ().Select ( character => ( byte ) character ).ToArray () );
}
关键是将字符串转换为字节[]可以使用LINQ完成:
.ToCharArray ().Select ( character => ( byte ) character ).ToArray () )
反过来说:
.Select ( character => ( char ) character ).ToArray () )