Rfc2898DeriveBytes 的版本无关代码(在 .NET 4.0 上有 Dispose 但在 2.0 上没有)
Version-independent code for Rfc2898DeriveBytes (has Dispose on .NET 4.0 but not on 2.0)
我正在编写一个使用 Rfc2898DeriveBytes
的小型 .NET 2.0 兼容程序集。在 .NET 2.0 上 Rfc2898DeriveBytes
不实现 IDisposable
,而在 .NET 4.0 中 Rfc2898DeriveBytes
实现 IDisposable
.
我的程序集加载到 .NET 4.0 应用程序和 .NET 2.0 应用程序中。
我需要 Dispose
Rfc2898DeriveBytes
使用 .NET 4.0 还是可以像使用 MemoryStream
一样忽略它?如果是这样,我如何编写 .NET 2.0 和 .NET 4.0 兼容代码,仅在 .NET 4.0 上调用 Dispose
? (最好不要反射等等。)
我想不在 class 上使用 Dispose
并不危险,因为 IDisposable
来自 abstract
DeriveBytes
-class。
你可以:
Rfc2898DeriveBytes rfc = null;
try
{
var salt = new byte[128];
rfc = new Rfc2898DeriveBytes("password", salt);
}
finally
{
IDisposable disp = rfc as IDisposable;
if (disp != null)
{
disp.Dispose();
}
}
即使使用 Roslyn,编译器也不会删除 as IDisposable
:http://goo.gl/OObkzv(右窗格,它已经处于发布模式,因此优化处于活动状态)
(请注意,我并不是完全复制 using
模式...我已经在 try
/finally
内部而不是外部初始化了 rfc
变量...可能没有实际区别)
我正在编写一个使用 Rfc2898DeriveBytes
的小型 .NET 2.0 兼容程序集。在 .NET 2.0 上 Rfc2898DeriveBytes
不实现 IDisposable
,而在 .NET 4.0 中 Rfc2898DeriveBytes
实现 IDisposable
.
我的程序集加载到 .NET 4.0 应用程序和 .NET 2.0 应用程序中。
我需要 Dispose
Rfc2898DeriveBytes
使用 .NET 4.0 还是可以像使用 MemoryStream
一样忽略它?如果是这样,我如何编写 .NET 2.0 和 .NET 4.0 兼容代码,仅在 .NET 4.0 上调用 Dispose
? (最好不要反射等等。)
我想不在 class 上使用 Dispose
并不危险,因为 IDisposable
来自 abstract
DeriveBytes
-class。
你可以:
Rfc2898DeriveBytes rfc = null;
try
{
var salt = new byte[128];
rfc = new Rfc2898DeriveBytes("password", salt);
}
finally
{
IDisposable disp = rfc as IDisposable;
if (disp != null)
{
disp.Dispose();
}
}
即使使用 Roslyn,编译器也不会删除 as IDisposable
:http://goo.gl/OObkzv(右窗格,它已经处于发布模式,因此优化处于活动状态)
(请注意,我并不是完全复制 using
模式...我已经在 try
/finally
内部而不是外部初始化了 rfc
变量...可能没有实际区别)