C# 对静态对象使用块使用
我正在将一些代码添加到 C# 程序中的 using
块中。 我正在将我的应用程序(以前是独立的)填充到现有的代码体中,因此我需要做一些调整才能使其正确适应。 它最终看起来如下:
public class WrapperForMyOldApp
{
public static ItemThatINeed item1;
public static ItemThatINeed item2;
public WrapperForMyOldApp ()
{
item1 = new ItemThatINeed();
item2 = new ItemThatINeed();
}
public static go()
{
// some stuff that i need to do with items 1 and 2
}
}
public class MainProgram
{
.
.
.
public void MethodThatNeedsToMakeUseOfMyApp ()
{
....
using (WrapperForMyOldApp oldAPp = new WrapperForMyOldApp())
{
WrapperForMyOldApp.go();
}
}
}
好吧,所以这里的问题是:我现在是否削弱了 using 块的效果和/或创建了任何可能对 MainProgram 类产生不利影响的特殊副作用? 我相信 Wrapper 对象及其内容将被处理并且执行将按预期继续,但是有什么我需要注意的事情吗?
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的包装类是否实现了 IDisposable 而您只是没有显示它? 如果它不是一次性的,那么您根本不需要 using 语句。
Does your wrapper class implement IDisposable and you're just not showing it? If it's not disposable, then you don't need the using statement at all.
为了使其工作,您需要让 WrapperForMyOldApp 实现 IDisposable。
然后,WrapperForMyOldApp 中的 Dispose() 调用将进行清理。
然而,静态对象通常用于生命周期超出单个对象的对象。 一般来说,对于这种类型的使用,您可以将 ItemThatINeed 实例设为非静态,在 WrapperForMyOldApp 构造函数中生成它们,然后在 WrapperForMyOldApp.Dispose() 中清理它们。
对于静态对象,您可能会造成一场噩梦 - 您正在构造该对象,然后说您想要执行清理(在 using 块的末尾),因此您的 Dispose() 方法将清理静态对象对象。 但是,如果再次使用它们,会发生什么? 如果您在 2 个线程中创建两个 WrapperForMyOldApp 实例,正确的行为是什么? 如果您想要确定性清理,我会考虑这些问题。
In order for this to work, you'll need to have WrapperForMyOldApp implement IDisposable.
The Dispose() call in WrapperForMyOldApp would then do your cleanup.
However, static objects are typically used for objects that have a lifetime beyond the single object. In general, for this type of usage, you'd make the ItemThatINeed instances non-static, generate them in your WrapperForMyOldApp constructor, then clean them up in WrapperForMyOldApp.Dispose().
With static objects, you're potentially creating a nightmare - you're constructing the object, and then saying you want to perform the cleanup (at the end of the using block), so you Dispose() method would be cleaning up the static objects. However, if they get used again, what should happen? What is the correct behavior if you create two WrapperForMyOldApp instances in 2 threads? I would consider these issues if you want deterministic cleanup.
好吧,如果
WrapperForMyOldApp
实现了IDisposable
,并且您的Dispose()
实现可以确保摆脱任何资源,那么它应该可以工作。但可能还有其他副作用。 该代码可以更改全局(静态)状态,例如文化等。它可以生成线程。 各种各样的事情。这不是一个坏方法,但您需要知道您封装的代码的作用,才能知道 Dispose() 是否会执行任何有用的操作。
Well, if
WrapperForMyOldApp
implementsIDisposable
, and yourDispose()
implementation can be sure to get rid of any resources, then it should work... but there can be other side effects. The code could change global (static) state, such as culture etc. It could spawn threads. All sorts of things.It isn't a bad approach, but you need to know what the code you are encapsulating does to know whether
Dispose()
is going to do anything useful.