无法隐式转换string类型为byte [](Cannot implicitly convert t

2019-06-24 21:46发布

我有一个加密用盐腌哈希密码的类。

但是如果我想空传递给该类我收到以下错误: Cannot implicitly convert type string to byte[]

下面是类代码:

public class MyHash
{
    public static string ComputeHash(string plainText, 
                            string hashAlgorithm, byte[] saltBytes)
    {
        Hash Code
    }
}

当我使用类我得到的错误:“无法隐式转换string类型为byte []”

//Encrypt Password
byte[] NoHash = null;
byte[] encds = MyHash.ComputeHash(Password, "SHA256", NoHash);

Answer 1:

您的返回类型ComputeHash函数是一个string 。 你尝试分配你的函数的结果encds ,这是byte[] 编译器分这种差异出来给你,因为从没有隐式转换stringbyte[]



Answer 2:

这是因为你的“ComputeHash”方法返回一个字符串,并且你想这个返回值分配给一个字节数组;

byte[] encds = MyHash.ComputeHash(Password, "SHA256", NoHash);

有,因为存在许多不同的编码来表示一个字符串作为字节,如ASCII或UTF8字符串为byte []没有隐式 converstion。

您需要使用适当的编码类,像这样明确地将bytes;

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


文章来源: Cannot implicitly convert type string to byte[]