问题描述
我想创建一个返回一个XmlReader的方法。根据情况的XmlReader的可馈送不同类型的流,或者是StringReader或一个MemoryStream
I would like to create a method that returns an XmlReader. Depending on the circumstances the XmlReader may be fed different types of streams, either a StringReader or a MemoryStream.
通常我处理一个StringReader或的MemoryStream与使用块,但因为我想返回一个XmlReader而不是,我不能这样做,如果我想去这种设计。我不希望将MemoryStream分配大量内存,这样我就可以住在资源释放轻微的延迟。
Normally I dispose a StringReader or MemoryStream with a using block, but since I want to return an XmlReader instead, I cannot do that if I want to go with this design.I don't expect the MemoryStream to allocate huge amounts of memory, so I can live with a slight delay in resource deallocation.
是让GC处置StringReader和的MemoryStream可以接受的,这种情况下的后果?
Are the consequences of letting the GC dispose StringReader and MemoryStream acceptable in this case?
我要澄清,这是一个的实际的问题不是的最佳实践的问题。显然,理论决定了我要清理自己的资源分配,但理论上也说我应该preFER尽可能简单的设计,最大的可维护性。在某些情况下,突破的最佳实践可恕我直言,是合理的,我的问题是具体的案件是否正当突破的最佳实践。
I should clarify that this is a practical question not a best-practice question. Obviously the theory dictates that I should clean up my own resource allocations, but theory also says that I should prefer the simplest possible design for maximum maintainability. In some cases breaking best-practice can IMHO be justified and my question is whether this concrete case justifies breaking best-practice.
此外,这是的只有的有关StringReader和MemoryStream的,不是一般的流或阅读器。我的理由证明它在这种情况下是,StringReader / MemoryStream的实际创建是公封装在返回的XmlReader的方法中,因此,它是在控制之下,该XmlReader的将不被馈以有限的资源的流。
Also this is only about StringReader and MemoryStream, not a general stream or reader.My reason for justifying it in this case is that the actual creation of the StringReader / MemoryStream is well encapsulated in the method that returns the XmlReader, hence it is under control that the XmlReader will not be fed a stream with a limited resource.
推荐答案
没有什么会在这种情况下吃亏,但国际海事组织它仍然是非常不好的做法。你拥有它们 - 为什么不这样做是否正确?其实,的处理的一个的MemoryStream
还是不能释放等 - 它仍然是由GC约束。但在这里的某个地方出与众不同的code气味。这可以成为的真正的,如果什么都没有改变,突然它不是问题的MemoryStream
但别的东西,等等。
Nothing is going to suffer in this case, but IMO it is still very bad practice. You own them - why not do it properly? Actually, disposing a MemoryStream
still can't deallocate etc - it is still bound by GC. But there is a distinct code smell in here somewhere. This can become real problems if anything ever changes, and suddenly it isn't a MemoryStream
but something else, etc.
我们不能让的你处理它,但个人:我很挑剔我的使用
取值
We can't make you dispose it, but personally: I am fastidious about my using
s
这篇关于是否确定不要丢弃一个MemoryStream / StringReader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!