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


当前回答

总之,当您使用实现IDisposable类型的局部变量时,总是毫无例外地使用using1。

如果使用非局部IDisposable变量,则始终实现IDisposable模式。

两条简单的规则,无一例外。否则,防止资源泄漏是一件非常痛苦的事情。


1):唯一的例外是-当你处理异常时。在finally块中显式调用Dispose的代码可能会更少。

其他回答

另一个对象立即被处置的合理使用的例子:

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了它,这至少会浪费资源。

只是添加了一点我很惊讶没有出现的东西。using最有趣的特性(在我看来)是无论你如何退出using块,它总是会释放对象。这包括返回和异常。

using (var db = new DbContext())
{
    if(db.State == State.Closed)
        throw new Exception("Database connection is closed.");
    return db.Something.ToList();
}

这与是否抛出异常或是否返回列表无关。DbContext对象总是会被释放。

Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:

namespace HelloWorld
{
    using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
    public class Startup
    {
        public static AppFunc OrderEvents() 
        {
            AppFunc appFunc = (IDictionary<DateTime, string> events) =>
            {
                if ((events != null) && (events.Count > 0))
                {
                    List<string> result = events.OrderBy(ev => ev.Key)
                        .Select(ev => ev.Value)
                        .ToList();
                    return result;
                }
                throw new ArgumentException("Event dictionary is null or empty.");
            };
            return appFunc;
        }
    }
}

这是一种明智的做法,因为滥用这种做法会损害代码的清晰性。在DotNetPearls (http://www.dotnetperls.com/using-alias)中有一个关于c#别名的很好的解释,也提到了优点和缺点。

总之,当您使用实现IDisposable类型的局部变量时,总是毫无例外地使用using1。

如果使用非局部IDisposable变量,则始终实现IDisposable模式。

两条简单的规则,无一例外。否则,防止资源泄漏是一件非常痛苦的事情。


1):唯一的例外是-当你处理异常时。在finally块中显式调用Dispose的代码可能会更少。