用户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 (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语句的原因是为了确保对象一旦超出作用域就会被释放,并且不需要显式代码来确保发生这种情况。

正如在理解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 LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;

正如你所看到的,这被称为使用别名指令,它可以用来隐藏冗长的引用,如果你想在你的代码中明显地引用什么 如。

LegacyEntities.Account

而不是

CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account

或者简单地

Account   // It is not obvious this is a legacy entity

在过去,我经常使用它来处理输入和输出流。您可以很好地嵌套它们,这消除了您通常遇到的许多潜在问题(通过自动调用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();
                }
            }
        }

当使用ADO时。NET中,你可以在connection对象或reader对象上使用keywork。这样,当代码块完成时,它将自动处理您的连接。