我正在把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;

然后使用下面的代码

string input = "some text"; 
byte[] array = Encoding.ASCII.GetBytes(input);

希望能解决!

其他回答

这个问题已经被回答了很多,但对我来说,唯一的工作方法是:

    public static byte[] StringToByteArray(string str)
    {
        byte[] array = Convert.FromBase64String(str);
        return array;
    }

如果您已经有了一个字节数组,那么您将需要知道使用了什么类型的编码使其成为字节数组。

例如,如果字节数组是这样创建的:

byte[] bytes = Encoding.ASCII.GetBytes(someString);

你需要把它转换回一个字符串,就像这样:

string someString = Encoding.ASCII.GetString(bytes);

如果可以在继承的代码中找到用于创建字节数组的编码,则应该进行设置。

这个问题已经回答过很多次了,但是随着c# 7.2和Span类型的引入,在不安全的代码中有一种更快的方法来做到这一点:

public static class StringSupport
{
    private static readonly int _charSize = sizeof(char);

    public static unsafe byte[] GetBytes(string str)
    {
        if (str == null) throw new ArgumentNullException(nameof(str));
        if (str.Length == 0) return new byte[0];

        fixed (char* p = str)
        {
            return new Span<byte>(p, str.Length * _charSize).ToArray();
        }
    }

    public static unsafe string GetString(byte[] bytes)
    {
        if (bytes == null) throw new ArgumentNullException(nameof(bytes));
        if (bytes.Length % _charSize != 0) throw new ArgumentException($"Invalid {nameof(bytes)} length");
        if (bytes.Length == 0) return string.Empty;

        fixed (byte* p = bytes)
        {
            return new string(new Span<char>(p, bytes.Length / _charSize));
        }
    }
}

请记住,字节表示UTF-16编码的字符串(在c#领域称为“Unicode”)。

一些快速的基准测试表明,对于中等大小的字符串(30-50个字符),上述方法大约比它们的Encoding.Unicode.GetBytes(…)/GetString(…)实现快5倍,对于较大的字符串甚至更快。这些方法似乎也比使用Marshal.Copy(..)或Buffer.MemoryCopy(…)的指针更快。

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);
}

你也可以使用扩展方法为字符串类型添加一个方法,如下所示:

static class Helper
{
   public static byte[] ToByteArray(this string str)
   {
      return System.Text.Encoding.ASCII.GetBytes(str);
   }
}

然后像下面这样使用它:

string foo = "bla bla";
byte[] result = foo.ToByteArray();