用户kokos通过使用关键字回答了c#的隐藏特性问题。你能详细说明一下吗?使用的用途是什么?
当前回答
使用,在某种意义上
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子句用于定义特定变量的作用域。
例如:
Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
Conn.Open()
// Execute SQL statements here.
// You do not have to close the connection explicitly
// here as "USING" will close the connection once the
// object Conn goes out of the defined scope.
}
在过去,我经常使用它来处理输入和输出流。您可以很好地嵌套它们,这消除了您通常遇到的许多潜在问题(通过自动调用dispose)。例如:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (System.IO.StreamReader sr = new StreamReader(bs))
{
string output = sr.ReadToEnd();
}
}
}
使用,在某种意义上
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);
}
}
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.
这允许您使用非常好的使用语法来指示所述操作的显式开始和结束。这也是系统如何。事务处理可以工作。
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间