Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

c# - Determining if IDisposable should extend an interface or be implemented on a class implementing said interface

How can I determine if I should extend one of my interfaces with IDisposable or implement IDisposable on a class that implements my interface?

I have an interface that does not need to dispose of any external resources, except for one particular implementation. My options seem to be:

1) Implement IDisposable on the interface requiring all of the implementations to implement Dispose, even if only an empty method.

-or-

2) Implement IDisposable on only the classes that have resources needing to be disposed. This will cause problems with "using" because my object is created from a factory and therefore all upstream code works against the interface. Since the interface is not bound to IDisposable, "using" does not see the Dispose method. However, I could cast the factory result to the implementation; however, that then makes the consumer aware of the implementation, defeating the purpose of interfaces.

Any ideas as to best practices?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you expect callers to only be able to interact with the interface, and never the implementation, then you want to have the interface extend IDisposable. If not, they'll need to check if the value is IDisposable anyway to see if it needs to be disposed.

If the object responsible for disposing of the object knows of the concrete implementation, and it is only ever objects that are given references to it (but aren't responsible for disposing of it) that use the interface, then consider the second option.

A good example of the first option is IEnumerator. Many IEnumerator objects don't need to do anything when they're disposed, but some do, and so the interface extends IDisposable because the object responsible for the creation/lifecycle of that object will (or should) never have knowledge of the underlying implementation.

An example of the second would be something like IComparer many objects that need to be compared are disposable, but the sections of code using an object through the interface aren't responsible for it's creation/lifecycle, so it needs no knowledge of whether or not that type is disposable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...