2013-07-02 3 views
1

나는스트림이 바인드 되었습니까?

Stream str = new FileStream(somefile, FileMode.OpenOrCreate); 
Stream newstr = str; 
str.Dispose(); // I disposed only str and not new str 

byte[] b = new byte[newstr.Length];// got exception here stating unable to access closed stream... 

아래로 다른 할당하고 처분하는 내 스트림을하는 동안 예외 건너 온 이유는 ...? 나는 C# 및 Stream을 처음 사용합니다. Stream이 네임 스페이스 System.IO에있는 곳입니다.

답변

3

예, str.Dispose으로 전화하면 newStr도 처리됩니다. Stream은 .NET의 모든 클래스와 마찬가지로 reference types입니다. Stream newstr = str을 쓸 때 새로 Stream을 만들지 않고 과 동일한Stream에 대한 새 참조를 만들면됩니다.

올바른 방법이 될 것이라고 쓰기 :

Stream str = new FileStream(somefile, FileMode.OpenOrCreate); 
int strLen = str.Length; 
str.Dispose(); 

byte[] b = new byte[strLen]; 

이 어떤 ObjectDisposedException 년대를 방지 할 수 있습니다. intvalue type이므로 int strLen = str.Length이라고 쓰면 이고 값의 새 복사본이 만들어지고 변수 strLen에 저장됩니다. 따라서 Stream이 삭제 된 후에도 해당 값을 사용할 수 있습니다.

+0

고맙습니다. .. 알았습니다. –

관련 문제