在C#中,如果一个类,如管理器类,没有资源,是那里有它任何好处:IDisposable的
简单的例子:
公共接口IBoxManager { INT addBox (箱b)条; } 公共类BoxManager:IBoxManager {公众诠释addBox(箱B) {使用(DataContext的DB =新的DataContext ()){ db.Boxes.add(二); db.SaveChanges(); } 返回b.id; } }
会不会有在内存中使用任何好处使用BoxManager时如果它也实现IDisposable? 公共类BoxManager:IBoxManager,IDisposable的
例如:
BoxManager BM =新BoxManager(); bm.add(myBox上); bm.dispose(); //是否有利于这样做呢?解决方案
有只有2个原因实施 IDisposable的上一个类型
- 类型包含必须释放本地资源时,类型不再使用
- 的类型包含类型的IDisposable
如果这些都不是真的,那么不执行的IDisposable
修改
有几个人提到,的IDisposable 是实现开始/结束或bookended操作的好方法。虽然这不是的IDisposable 的原意它确实提供了一个很好的模式。
类操作{类助手:IDisposable的{内部操作操作; 公共无效的Dispose(){ Operation.EndOperation(); } } 公共IDisposable的BeginOperation(){:返回新助手(){操作=此}; } 私人无效EndOperation(){:} }注:实现这个模式的另一个有趣的方法是使用lambda表达式。而不是给一个的IDisposable 返回给用户,并希望他们不要忘了叫的Dispose 让他们给你拉姆达,使他们能够执行操作,并关闭了操作
公共无效BeginOperation(行动行动){ BeginOperationCore(); 尝试{动作(); } {最后 EndOperation(); } }
In C#, if a class, such as a manager class, does not have resources, is there any benefit to having it : IDisposable?
Simple example:
public interface IBoxManager { int addBox(Box b); } public class BoxManager : IBoxManager { public int addBox(Box b) { using(dataContext db = new dataContext()){ db.Boxes.add(b); db.SaveChanges(); } return b.id; } }Will there be any benefit in memory use when using BoxManager if it also implements IDisposable? public class BoxManager : IBoxManager , IDisposable
For example:
BoxManager bm = new BoxManager(); bm.add(myBox); bm.dispose();//is there benefit to doing this?解决方案
There are only 2 reasons for implementing IDisposable on a type
- The type contains native resources which must be freed when the type is no longer used
- The type contains fields of type IDisposable
If neither of these are true then don't implement IDisposable
EDIT
Several people have mentioned that IDisposable is a nice way to implement begin / end or bookended operations. While that's not the original intent of IDisposable it does provide for a very nice pattern.
class Operation { class Helper : IDisposable { internal Operation Operation; public void Dispose() { Operation.EndOperation(); } } public IDisposable BeginOperation() { ... return new Helper() { Operation = this }; } private void EndOperation() { ... } }Note: Another interesting way to implement this pattern is with lambdas. Instead of giving an IDisposable back to the user and hoping they don't forget to call Dispose have them give you a lambda in which they can execute the operation and you close out the operation
public void BeginOperation(Action action) { BeginOperationCore(); try { action(); } finally { EndOperation(); } }
更多推荐
有没有对不具备资源类实现IDisposable的任何好处?
发布评论