gpt4 book ai didi

c# - 在 C# 中处理对象

转载 作者:行者123 更新时间:2023-11-30 13:22:53 24 4
gpt4 key购买 nike

我写了下面的类:

public class CoupleFrames
{
public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
this.colorFrame = cif;
this.desktopFrame = df;
}

public ColorImageFrame colorFrame;
public Bitmap desktopFrame;
}

现在我使用以下代码来处理变量。

CoupleFrames cf = new CoupleFrames(frame1, frame2);
// some code...
cf.colorFrame.Dispose();
cf.desktopFrame.Dispose();

我不确定这是正确的方法。有人可以建议我处理整个对象的正确方法吗?

最佳答案

I'm not sure that this is the correct way. Someone can suggest me the correct way for disposing the entire object?

当然 - 你应该让 CoupleFrames 实现 IDisposable它的 Dispose 方法应该处理它的对象“拥有”。例如:

public sealed class CoupleFrames : IDisposable
{
private readonly ColorImageFrame colorFrame;
private readonly Bitmap desktopFrame;

public CoupleFrames(ColorImageFrame cif, Bitmap df)
{
// TODO: Argument validation, unless it's valid for these parameters
// to be null, in which case the Dispose method would need to be careful.
this.colorFrame = cif;
this.desktopFrame = df;
}

public void Dispose()
{
colorFrame.Dispose();
desktopFrame.Dispose();
}
}

注意几点:

  • 您应该确保CoupleFrame 确实“拥有”这些构成对象。处置依赖于清晰的所有权模式
  • 如果 CoupleFrame 没有密封(而且也不可能),您可能需要使用虚拟方法和终结器来进入更复杂的模式。它可能会变得非常复杂,您应该阅读 advice given here by Joe Duffy et al .如果你的类(class)是密封的,那么很多复杂性就会消失
  • 公共(public)字段通常不是一个好主意(就封装而言),这就是我在这里将它们设为私有(private)的原因。我还把它们设为只读,就好像它们以后可以更改一样,您需要考虑更改它们是否应该处理以前引用的对象等。
  • 通过使 CoupleFrame 实现 IDisposable,您基本上是在告诉所有客户他们应该处置他们拥有的任何实例。如果您对强加这种负担不满意,则需要稍微重新考虑一下设计。

关于c# - 在 C# 中处理对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17315967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com