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

有什么建议吗?


当前回答

在c# 11中,你可以使用UTF-8字符串字面量,这使得它超级简单,具有更好的性能,并且没有内存分配。

byte[] array = "some text";

或者,如果你已经有一个字符串值:

string input = "some text"; 
byte[] array = input;

这是一个使用旧的UTF-8编码方式(GetBytes)和c# 11 UTF-8字符串文字方式(GetBytesNew)之间的区别的例子。

其他回答

首先,添加系统。文本名称空间

using System.Text;

然后使用下面的代码

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

希望能解决!

使用这个

byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);

这个问题已经回答过很多次了,但是随着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(…)的指针更快。

在c# 11中,你可以使用UTF-8字符串字面量,这使得它超级简单,具有更好的性能,并且没有内存分配。

byte[] array = "some text";

或者,如果你已经有一个字符串值:

string input = "some text"; 
byte[] array = input;

这是一个使用旧的UTF-8编码方式(GetBytes)和c# 11 UTF-8字符串文字方式(GetBytesNew)之间的区别的例子。

基于阿里的回答,我会推荐一个扩展方法,允许你有选择地传入你想使用的编码:

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