【问题标题】:'System.Security.Cryptography.Rfc2898DeriveBytes': type used in a using statement must be implicitly convertible to System.IDisposable'System.Security.Cryptography.Rfc2898DeriveBytes':在 using 语句中使用的类型必须可隐式转换为 System.IDisposable
【发布时间】:2018-01-16 23:28:16
【问题描述】:

我的代码在 .Net 框架 4.5 中工作,但是当我尝试在 .Net 框架 2.0 中编写相同的代码时,它给出了编译错误

'System.Security.Cryptography.Rfc2898DeriveBytes':在 a 中使用的类型 using 语句必须隐式转换为 System.IDisposable

如何解决?

代码

[ComVisible(true)]
    public string HashPassword(string password)
    {

        byte[] salt;
        byte[] subkey;
        using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount))
        {
            salt = deriveBytes.Salt;
            subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
        }

        var outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];
        //some more code goes here
        return Convert.ToBase64String(outputBytes);
    }

【问题讨论】:

  • 该错误表明您只能初始化从 IDispossble 接口继承的类的实例,并且 Rfc2898DeriveBytes 类不继承 IDisposable 接口。这就是您看到此错误的原因
  • @ChetanRanpariya 这不正确。它继承自 DeriveBytes,后者实现了 IDisposable 接口。
  • 查看文档,不清楚IDisposable接口是否由.NET Framework 2.0中的抽象DeriveBytes类实现...
  • @Samra 检查您的 derivedBytes 变量是否有权访问 Dispose 方法.. Intellisense 是否批准 derivedBytes.Dispose() ?
  • DeriveBytes 在 .net 2.0 中没有实现 IDisposable。 msdn.microsoft.com/en-us/library/…

标签: c# .net using


【解决方案1】:

André's 评论中汲取灵感,看来Dispose 方法直到.NET 4 才引入:DeriveBytes.Dispose (注:“其他版本”)

您可以查看Dispose 方法在当前框架中是如何实现的,并考虑将其应用于您的项目:Source Browser

【讨论】:

  • 谢谢 Lachlan 我已经删除了 using 语句。这样可以吗?还是有更好的方法?
【解决方案2】:

如果你删除using 怎么样:

 Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, 
 PBKDF2IterCount);
 salt = deriveBytes.Salt;
 subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);

【讨论】:

  • 是的,这就是我在 cmets 中向 Lachlan 提出的要求并做到了! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多