是否可以在 C# 中强制使用 using 语句 [英] Is it possible to enforce the use of a using statement in C#

查看:29
本文介绍了是否可以在 C# 中强制使用 using 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的希望能够用某种属性来装饰我的类,该属性将强制使用 using 语句,以便始终安全地处理该类并避免内存泄漏.有人知道这种技术吗?

Would really like to be able to decorate my class with an attribute of some sort that would enforce the use of a using statement so that the class will always be safely disposed and avoid memory leaks. Anyone know of such a technique?

推荐答案

嗯,有一种方法可以做到这一点 - 只允许通过采用委托的静态方法访问您的对象.作为一个非常简单的例子(显然有许多不同的打开文件的方式 - 读/写等):

Well, there's one way you could sort of do it - only allow access to your object via a static method which takes a delegate. As a very much simplified example (as obviously there are many different ways of opening a file - read/write etc):

public static void WorkWithFile(string filename, Action<FileStream> action)
{
    using (FileStream stream = File.OpenRead(filename))
    {
        action(stream);
    }
}

如果能够创建一次性对象实例的唯一方法是您自己的类中的方法,您可以确保它们得到适当的使用.诚然,没有什么可以阻止委托获取引用的副本并在以后尝试使用它,但这并不是完全相同的问题.

If the only things capable of creating an instance of your disposable object are methods within your own class, you can make sure they get used appropriately. Admittedly there's nothing to stop the delegate from taking a copy of the reference and trying to use it later, but that's not quite the same problem.

当然,这种技术严重限制了您可以对对象执行的操作 - 但在某些情况下它可能很有用.

This technique severely limits what you can do with your object, of course - but in some cases it may be useful.

这篇关于是否可以在 C# 中强制使用 using 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆