用户kokos通过使用关键字回答了c#的隐藏特性问题。你能详细说明一下吗?使用的用途是什么?


当前回答

public class ClassA:IDisposable
{
    #region IDisposable Members
    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
    #endregion
}

public void fn_Data()
{
    using (ClassA ObjectName = new ClassA())
    {
        // Use objectName
    }
}

其他回答

using可以用来调用IDisposable。它还可以用于别名类型。

using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;

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.
}

“using”还可以用于解决名称空间冲突。

关于这个主题,我写了一个简短的教程,请参阅http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/。

当你使用using时,它将调用using作用域末端对象上的Dispose()方法。因此,在Dispose()方法中可以有相当多出色的清理代码。

要点:

如果您实现了IDisposable,请确保在Dispose()实现中调用GC.SuppressFinalize(),否则自动垃圾收集将尝试出现并在某个时刻Finalize它,如果您已经Dispose()d了它,这至少会浪费资源。

可以通过以下示例使用别名命名空间:

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