How do I create a extension method that uses a profile similar to using in C#
I am trying to create a method that looks like the following when used:
Dialog (var d = new MyDialog())
开发者_如何学编程{
d.DoSomethingToAVisibleDialogThatAppearedInTheDialog(); //Call
}
Like "using", it would handle the destructor, but I want to add more stuff to Dialog, which would handle my IDialog interface.
You could created a class like the following:
class DisposableWrapper<T> : where T : IDisposable {
T _wrapped;
private bool _disposed;
public DisposableWrapper(T wrapped) {
_wrapped = wrapped;
}
public T Item {
get { return _wrapped; }
}
public ~DisposableWrapper()
{
Dispose(false);
GC.SuppressFinalize(this);
}
public void Dispose() {
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing) {
_disposed = true;
((IDisposable)_wrapped).Dispose();
// do extra stuff
}
}
}
And then use it like so:
using (var wrapper = new DisposableWrapper(new Dialog()) {
Dialog d = wrapper.Item;
// do stuff
}
using
is a language feature, and specific to IDisposable
. It cannot be extended directly for different semantics. What you're trying would basically be adding a new feature to the language, which is not possible.
The best option is typically to provide an action, ideally in a generic method with a new()
constraint.
public static void Dialog<T>(Action<T> action) where T: IDialog, new()
{
var d = new T();
try
{
action(d);
}
finally
{
var idialog = d as IDialog;
if (idialog != null)
{
idialog.Dispose(); // Or whatever IDialog method(s) you want
}
}
}
You could then do:
Dialog(d => d.DoSomethingToAVisibleDialogThatAppearedInTheDialog());
I wrote up a class that does this called ResourceReleaser<T>.
Typical usage:
public class StreamPositionRestorer : ResourceReleaser<long>
{
public StreamPositionRestorer(Stream s) : base(s.Position, x => s.Seek(x)) { }
}
the end result of this example is that when you do this:
using (var restorer = new StreamPositionRestorer(stm)) {
// code that mucks with the stream all it wants...
}
// at this point the stream position has been returned to the original point
精彩评论