【问题标题】:Cannot implicitly convert type string to byte[]无法将类型字符串隐式转换为字节 []
【发布时间】:2012-05-29 02:05:51
【问题描述】:

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

但如果我想将 null 传递给类,则会收到以下错误:Cannot implicitly convert type string to byte[]

这是课程代码:

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

当我使用该类时,我收到错误:“无法将类型字符串隐式转换为字节 []”

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

【问题讨论】:

  • strings 是否应该可以转换为byte[]

标签: c# string c#-4.0 encoding


【解决方案1】:

这是因为您的 'ComputeHash' 方法返回一个字符串,而您正试图将此返回值分配给一个字节数组;

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

字符串到字节[] 没有隐式转换,因为存在许多不同的编码来将字符串表示为字节,例如 ASCII 或 UTF8。

您需要像这样显式使用适当的编码类转换字节;

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      相关资源
      最近更新 更多