我正在研究 c# 中的函数式编程,这样我就可以减少代码中的副作用数量,并使测试更容易并泛化我的代码,从而使重构变得更容易。但是,我在弄清楚如何using
使用通用 using 块嵌套语句时遇到问题。考虑以下:
public static class Disposable
{
public static TResult Using<TDisposable, TResult>
(
Func<TDisposable> factory,
Func<TDisposable, TResult> fn) where TDisposable : IDisposable
{
using (var disposable = factory())
{
return fn(disposable);
}
}
}
我使用以下代码示例调用此代码:
Disposable.Using(
StreamFactory.GetStream,
stream => new byte[stream.Length].Tee(b => stream.Read(b, 0, (int)stream.Length)))
我将这个修改后的using
语句的输出传递给管道中的另一个方法。
然而,我确实遇到了一个警告,我被卡住了。
如果我想使用嵌套的 using 语句,但对我想要传递的返回项进行修改怎么办?
Disposable
通过重用我上面存根的类来考虑以下内容:
Disposable.Using(
() => new PasswordDeriveBytes(PasswordConstants.CryptoKey, null),
password => Disposable.Using(
() => new RijndaelManaged(),
symmetricKey =>
Disposable.Using(
() => symmetricKey.CreateEncryptor(password.GetBytes(PasswordConstants.KeySize/8), Encoding.ASCII.GetBytes(PasswordConstants.Cipher)),
encryptor => encryptor)
));
此代码有效...但是,如果我想更改symmetricKey's
加密模式怎么办?
以下不起作用:
Disposable.Using(
() => new PasswordDeriveBytes(PasswordConstants.CryptoKey, null),
password => Disposable.Using(
() => new RijndaelManaged(),
symmetricKey =>
{
symmetricKey.Mode = CipherMode.CBC; // ← this causes an issue, and also the fact that I made a **code block** here
Disposable.Using(
() => symmetricKey.CreateEncryptor(password.GetBytes(PasswordConstants.KeySize/8), Encoding.ASCII.GetBytes(PasswordConstants.Cipher)),
encryptor => encryptor);
}
));
我能做些什么来允许修改通过Disposable.Using
我上面创建的通用方法传递的变量?