我应该安排一名字符串作家吗?或以某种方式重复使用? [英] Should i dispose a stringwriter? or reuse somehow?

查看:61
本文介绍了我应该安排一名字符串作家吗?或以某种方式重复使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使其变得简单。我有一个字符串编写器作为类成员,因此我不能使用using()。每当我调用某个函数时,我都希望有一个空的sw。我应该在sw上调用Dispose()并分配一个新对象吗?还是我应该做类似.close()的事情,并做其他事情来清空缓冲区?

I'll make it simple. I have a stringwriter as a class member therefore i cannot use using(). I want an empty sw everytime i call a certain function. Should i call Dispose() on the sw and allocate a new object? or should i do something like .close() and do something else to empty the buffer?

推荐答案

我同意其他答复者,那么您应该查看您的设计,看看是否确实有使用类级字符串编写器的方法。

I agree with the other answerer, that you should look at your design to see if having the class level string writer is really the way to go.

但是,我不同意


它所做的只是回调到
基类中(TextWriter)处理-
什么都没有。

"All it does is call back into the base class' (TextWriter) Dispose -- which does nothing."

在使用类时,如果类型实现了 Dispose

When consuming classes, if a type implements Dispose, you really should call it, either explicitly or with a "using".

在这种情况下,确实是 StringWriter.Dispose 调用 TextWriter.Dispose 不会执行任何操作,但是我真的不建议只是忽略它。

In this case, it is true that StringWriter.Dispose calls down to TextWriter.Dispose which does nothing, but I really wouldn't advise "just ignoring it".

继承和多态的全部要点是可以将这种类型换成派生类型。

The whole point of inheritance and polymorphism is that this type can be swapped out for a derived type.

今天代码中的 StringWriter ,可能会替换为明天的 EvenBetterStringWriter 对于 Dispose 可能具有更有意义的实现。

Today's StringWriter in your code, may be swapped for tomorrow's EvenBetterStringWriter which may have a more meaningful implementation for Dispose.

如果它实现了 Dispose ,并且使用了它,则应该认真考虑完成后调用dispose。

If it implements Dispose, and you use it, you should seriously think about calling dispose when you are done.

以这种特定的具体实现的内部知识来指导设计时,这是很危险的。 StringWriter 类的作者明确地意味着要调用Dispose,否则就不会出现。

Having privileged knowledge of the internals of this specific concrete implementation is dangerous when you let it guide your design like this. The author of the StringWriter class clearly meant for Dispose to be called, or it wouldn't be there.

这篇关于我应该安排一名字符串作家吗?或以某种方式重复使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆