Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将类型字符串隐式转换为字节[]_C#_String_C# 4.0_Encoding - Fatal编程技术网

C# 无法将类型字符串隐式转换为字节[]

C# 无法将类型字符串隐式转换为字节[],c#,string,c#-4.0,encoding,C#,String,C# 4.0,Encoding,我有一个类,它用盐散列加密密码 但是如果我想将null传递给类,我会得到以下错误:无法将类型字符串隐式转换为字节[] 以下是课程代码: public class MyHash { public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes) { Hash Code } } 当我使

我有一个类,它用盐散列加密密码

但是如果我想将null传递给类,我会得到以下错误:
无法将类型字符串隐式转换为字节[]

以下是课程代码:

public class MyHash
{
    public static string ComputeHash(string plainText, 
                            string hashAlgorithm, byte[] saltBytes)
    {
        Hash Code
    }
}
当我使用该类时,我得到一个错误:“不能隐式地将类型字符串转换为字节[]”


这是因为您的“ComputeHash”方法返回一个字符串,并且您正在尝试将此返回值分配给一个字节数组,其中包含:

byte[] encds = MyHash.ComputeHash(Password, "SHA256", NoHash);
字符串到字节[]之间没有隐式对话,因为存在许多不同的编码来将字符串表示为字节,例如ASCII或UTF8

您需要显式地使用适当的编码类来转换字节,如下所示

string x = "somestring";
byte[] y = System.Text.Encoding.UTF8.GetBytes(x);

ComputeHash
函数的返回类型是
字符串
。您尝试将函数的结果分配给
encds
,即
字节[]
。编译器向您指出了这个差异,因为没有从
字符串
字节[]

的隐式转换
字符串
应该转换为
字节[]
string x = "somestring";
byte[] y = System.Text.Encoding.UTF8.GetBytes(x);