为什么以下代码不起作用:
class Program
{
static void Main ( string[ ] args )
{
SomeClass s = new SomeClass( );
s.GetType( ).GetField( "id" , System.Reflection.BindingFlags.NonPublic ) // sorry reasently updated to GetField from GetProperty...
.SetValue( s , "new value" );
}
}
class SomeClass
{
object id;
public object Id
{
get
{
return id;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图设置私有字段的值.
这是我得到的例外:
System.NullReferenceException未处理Message = Object引用未设置为对象的实例.来源= ConsoleApplication7
StackTrace:位于C:\ Users\Antonio\Desktop\ConsoleApplication7\ConsoleApplication7\Program.cs中的Program.Main(String [] args):位于System的System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,String [] args)的第18行. System.Threading.ExecutionContext.Run上的System.Threading.ThreadHelper.ThreadStart_Context(Object state)中的Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()中的AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)(ExecutionContext executionContext System.Threading.ThreadHelper.ThreadStart()中的System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态),ContextExallback回调,对象状态,布尔值ignoreSyncCtx:InnerException:
我最近遇到一个错误"ObjectDisposedException:无法访问已关闭的流"
[ObjectDisposedException: Cannot access a closed Stream.]
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +10184402
System.Security.Cryptography.CryptoStream.FlushFinalBlock() +114
System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) +48
Run Code Online (Sandbox Code Playgroud)
使用以下格式的代码时:
using (var stream = new MemoryStream())
{
using (var hashStream = new CryptoStream(stream,
new SHA256Managed(), CryptoStreamMode.Write))
using (var writer = new TextWriter(hashStream))
{
writer.Write("something");
}
// ^-- Exception occurs on hashStream Dispose
// While naively I assumed that TextWriter.Dispose wouldn't touch the
// underlying stream(s).
return stream.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
因此引发异常是因为TextWriter的Dispose释放了包装的Stream(hashStream).我的问题是这样的:
是否将此约定(使用默认构造函数/参数)应用于.NET中的所有流?
是否有佳能讨论这种资源使用模式?例如,可以假设CryptoStream会关闭MemoryStream吗?我知道答案,并且还有其他问题,但如果有这样的话,我希望它在设计指南方面得到解决.
这种行为记录在哪里?
如果我有一个CryptoStream我想传回给用户的话,天真的方法就是
public Stream GetDecryptedFileStream(string inputFile, byte[] key, byte[] iv)
{
var fsCrypt = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
var rmCrypto = new RijndaelManaged();
var transform = rmCrypto.CreateDecryptor(key, iv);
var cs = new CryptoStream(fsCrypt, transform, CryptoStreamMode.Read);
return cs;
}
Run Code Online (Sandbox Code Playgroud)
我知道,当我处置时CryptoStream,底层FileStream 也会被处置掉.我到运行的问题是我该怎么办与rmCrypto和transform?RijndaelManaged并且ICryptoTransform是一次性类,但处理流不会处理这两个对象.
处理这种情况的正确方法是什么?