用于从字符串转换为字节的内置函数

Gra*_*ton 3 c#

我有以下功能:

public static byte[] StringToByte(string str)
{
    int length = str.Length;
    byte[] ba = new byte[length];
    for (int i = 0; i < length; i++)
    {           
        ba[i] = (byte)str[i];
    }
    return ba;
}
Run Code Online (Sandbox Code Playgroud)

我想知道这个方法是否有内置函数?

And*_*zub 9

System.Text.Encoding.GetBytes(string)
Run Code Online (Sandbox Code Playgroud)


Ash*_*pta 6

System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
byte[] bytes= encoding.GetBytes(stringData);
Run Code Online (Sandbox Code Playgroud)