用户kokos通过使用关键字回答了c#的隐藏特性问题。你能详细说明一下吗?使用的用途是什么?
当前回答
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
这允许您使用非常好的使用语法来指示所述操作的显式开始和结束。这也是系统如何。事务处理可以工作。
其他回答
对我来说,“using”这个名字有点令人困惑,因为它可以是一个导入Namespace的指令,也可以是一个用于错误处理的语句(就像这里讨论的那样)。
为错误处理取一个不同的名字会很好,而且可能是一个更明显的名字。
使用using语句的原因是为了确保对象一旦超出作用域就会被释放,并且不需要显式代码来确保发生这种情况。
正如在理解c#中的“using”语句(codeproject)和使用实现IDisposable的对象(microsoft)中,c#编译器转换
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
c# 8引入了一个新的语法,命名为“using declarations”:
using声明是一个前面有using关键字的变量声明。它告诉编译器,所声明的变量应该在封闭作用域的末尾被处理。
所以上面的等效代码是:
using var myRes = new MyResource();
myRes.DoSomething();
当控制离开包含范围(通常是一个方法,但也可以是一个代码块)时,myRes将被释放。
使用,在某种意义上
using (var foo = new Bar())
{
Baz();
}
实际上是try/finally块的简写。它等价于代码:
var foo = new Bar();
try
{
Baz();
}
finally
{
foo.Dispose();
}
当然,您会注意到,第一个代码片段比第二个代码片段简洁得多,而且即使抛出异常,您也可能希望在清理过程中执行许多类型的操作。因此,我们提出了一个称为Scope的类,它允许您在Dispose方法中执行任意代码。例如,如果你有一个名为IsWorking的属性,你总是想在尝试执行一个操作后将其设置为false,你会这样做:
using (new Scope(() => IsWorking = false))
{
IsWorking = true;
MundaneYetDangerousWork();
}
你可以在这里阅读更多关于我们的解以及我们是如何推导它的。
另一个对象立即被处置的合理使用的例子:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}
当你使用using时,它将调用using作用域末端对象上的Dispose()方法。因此,在Dispose()方法中可以有相当多出色的清理代码。
要点:
如果您实现了IDisposable,请确保在Dispose()实现中调用GC.SuppressFinalize(),否则自动垃圾收集将尝试出现并在某个时刻Finalize它,如果您已经Dispose()d了它,这至少会浪费资源。
推荐文章
- 不能在lambda表达式中使用ref或out参数
- c# int到字节[]
- 将WPF组合框绑定到自定义列表
- foreach vs somlist . foreach (){}
- 为什么try{…}最后{…}好;尝试{…} catch{}坏?
- c# 8用多种情况切换表达式,结果相同
- 在没有事件源注册的情况下写入Windows应用程序事件日志
- 并发HashSet<T>在。net框架?
- 从控制器内获得控制器和动作名称?
- 新建T()
- 如何将枚举绑定到WPF中的组合框控件?
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在