[英]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. 就像“使用”一样,它会处理析构函数,但我想在Dialog中添加更多东西,它将处理我的IDialog接口。
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
. using
是一种语言功能,特定于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. 最佳选择通常是提供一个动作,理想情况是在带有
new()
约束的泛型方法中。
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> . 我写了一个名为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.