整个类的 C# IDisposable 对象
我目前正在进行的项目在类中的每个方法中都使用 IDisposable 对象。在每个方法开始时重新输入 using 块已经开始变得乏味,并且想知道是否有一种方法可以指定在类的每个方法中使用的一次性变量?
public static class ResourceItemRepository
{
public static ResourceItem GetById(int id)
{
using (var db = DataContextFactory.Create<TestDataContext>())
{
// Code goes here...
}
}
public static List<ResourceItem> GetInCateogry(int catId)
{
using (var db = DataContextFactory.Create<TestDataContext>())
{
// Code goes here...
}
}
public static ResourceItem.Type GetType(int id)
{
using (var db = DataContextFactory.Create<TestDataContext>())
{
// Code goes here...
}
}
}
The project that I'm working on at the moment uses an IDisposable object in every method in a class. It has started getting tedious re-typing the using block at the start of every method, and was wondering if there was a way to specify a disposable variable for use in every method of the class?
public static class ResourceItemRepository
{
public static ResourceItem GetById(int id)
{
using (var db = DataContextFactory.Create<TestDataContext>())
{
// Code goes here...
}
}
public static List<ResourceItem> GetInCateogry(int catId)
{
using (var db = DataContextFactory.Create<TestDataContext>())
{
// Code goes here...
}
}
public static ResourceItem.Type GetType(int id)
{
using (var db = DataContextFactory.Create<TestDataContext>())
{
// Code goes here...
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,没有什么特别适合这个的。您可以写:
不过,我不确定这是否特别有益。
(请注意,我必须将其从原始版本中的
Action
更改为Func
因为您希望能够从你的方法。)No, there's nothing particularly geared towards this. You could write:
I'm not sure that it would be particularly beneficial though.
(Note that I've had to change it from
Action<TestDataContext>
in my original version toFunc<TestDataContext, T>
as you want to be able to return values from your methods.)坦率地说,我会保留冗长的代码,但使用片段而不是每次都键入它。
使用特殊工具创建自己的代码片段,或者使用文本替换工具,例如短信
Frankly, i'd keep the verbose code, but using a snippet instead of typing it all each time.
Either create your own snippet with a special tool or use text-replacement tools like Texter
也许简单的重构是您可以做的最好的事情,而无需求助于 PostSharp 之类的东西:
Maybe a simple refactoring is the best that you can do without resorting to something like PostSharp: