不好的做法? using语句C#中的非佳能公司的用法 [英] Bad practice? Non-canon usage of c#'s using statement

查看:97
本文介绍了不好的做法? using语句C#中的非佳能公司的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#有使用语句,专门为IDisposable的对象。据推测,在使用语句中指定的任何对象将持有某种资源应确定性地释放。

C# has the using statement, specifically for IDisposable objects. Presumably, any object specified in the using statement will hold some sort of resource that should be freed deterministically.

不过,在我看来,有编程许多设计其中有一个单一的,确定的开始和结束,但缺乏内在的语言支持。在使用构造提供了一个机会,利用内置的代码编辑器的功能,至少清楚,自然突出这样的设计或操作的范围。

However, it seems to me that there are many designs in programming which have a single, definite beginning and end, but lack intrinsic language support. The using construct provides an opportunity to use the built in features of a code editor to, at least, clearly and naturally highlight the scope of such a design or operation.

我心目中的排序操作的频繁与启动的BeginXXX() EndXXX()方法,虽然有很多不同的口味,如异步代码执行,涉及到开始和加盟的。

What I have in mind is the sort of operation that frequently starts with a BeginXXX() and EndXXX() method, though there are plenty of different flavors, such as an asynchronous code execution that involves a "start" and a "join".

拿这个简单的例子

webDataOperation.Start();
GetContentFromHardDrive();
webDataOperation.Join();
// Perform operation that requires data from both sources

如果,相反,开始方法返回一个对象,其 IDisposable.Dispose 方法执行连接操作。

What if, instead, the Start method returned an object whose IDisposable.Dispose method performs the join operation.

using(webDataOperation.Start()) {
    GetContentFromHardDrive();
}
// Perform operation that requires data from both sources

或数据的操作,更好的是,我曾专门记:我有一个对象,做非常专业的图形块传输,并有一个开始()结束()方法(设计也存在于DirectX和XNA)。相反...

Or, better yet, what I specifically had in mind: I have an object that does highly specialized graphics blitting and has a Begin() and End() method (a design also present in DirectX and XNA). Instead...

using(blitter.BlitOperation()) {
    // Do work
}
// Use result

这似乎是更加自然和可读性,但它是不可取,看到它使用了的IDisposable 接口和意外目的使用语句?换句话说,这会是不相上下与邻*在非直观的方式verloading运算符*?

It seems to be more natural and readable, but is it inadvisable, seeing as it uses the IDisposable interface and the using statement for unintended purposes? In other words, would this be on par with o*verloading an operator in a non-intuitive way*?

推荐答案

这是一个完全可以接受的做法。这些被称为保理类型和框架设计指南建议这样做只是这一点。

This is a perfectly acceptable practice. These are called Factored Types, and the Framework Design Guidelines recommends doing just this.

基本上,如果该类型包装的操作与特定的生命周期,使用了IDisposable和using语句成为考虑适当的事情。

Basically, if the type wraps an operation with a specific lifetime, using IDisposable and the using statement becomes an appropriate thing to consider.

其实我的博客上讲述这个特定的主题这里,以及

I actually blogged about this specific topic here, as well.

这篇关于不好的做法? using语句C#中的非佳能公司的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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