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


当前回答

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#别名的很好的解释,也提到了优点和缺点。

其他回答

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

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

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

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


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

Rhino模拟记录回放语法有趣地使用了using。

并不是说它非常重要,而是使用它还可以用来动态地更改资源。

是的,正如前面提到的,是一次性的,但是可能您特别不希望在执行的其余时间内它们与其他资源不匹配。所以你要把它处理掉,这样它就不会影响到其他地方。

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.

这允许您使用非常好的使用语法来指示所述操作的显式开始和结束。这也是系统如何。事务处理可以工作。