如何创建使用类似于 C# 中使用的配置文件的扩展方法
我正在尝试创建一个在使用时如下所示的方法:
Dialog (var d = new MyDialog())
{
d.DoSomethingToAVisibleDialogThatAppearedInTheDialog(); //Call
}
像“using”一样,它将处理析构函数,但我想向 Dialog 添加更多内容,它将处理我的 IDialog 接口。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一个如下所示的类:
然后像这样使用它:
You could created a class like the following:
And then use it like so:
using
是一项语言功能,特定于IDisposable
。它不能直接扩展为不同的语义。您所尝试的基本上是向该语言添加新功能,这是不可能的。最好的选择通常是提供一个操作,最好是使用带有
new()
约束的通用方法。然后你可以这样做:
using
is a language feature, and specific toIDisposable
. 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.You could then do:
我编写了一个名为 ResourceReleaser 。
典型用法:
此示例的最终结果是,当您执行此操作时:
I wrote up a class that does this called ResourceReleaser<T>.
Typical usage:
the end result of this example is that when you do this: