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


当前回答

Using as语句自动调用指定对象的dispose 对象。对象必须实现IDisposable接口。它是 可以在一条语句中使用多个对象,只要它们是 同类型的。

CLR将您的代码转换为CIL。using语句被转换成try和finally语句块。这就是using语句在CIL中的表示方式。使用语句可分为三个部分:获取、使用和处置。首先获取资源,然后使用包含finally子句的try语句。然后在finally子句中对对象进行处理。

其他回答

在c#中using关键字有以下两种用法。

As a directive Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page. Example: using System.IO; As a statement This is another way to use the using keyword in C#. It plays a vital role in improving performance in garbage collection. The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly. Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly. You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned. Example: string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"; using (SqlConnection conn = new SqlConnection(connString)) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers"; conn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1)); } }

在前面的代码中,我没有关闭任何连接;它会自动关闭。由于using语句(using (SqlConnection conn = new SqlConnection(connString)), using语句将自动调用conn. close(),对于SqlDataReader对象也是如此。并且如果发生任何异常,它将自动关闭连接。

有关更多信息,请参见在c#中使用的用法和重要性。

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

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

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

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

对我来说,“using”这个名字有点令人困惑,因为它可以是一个导入Namespace的指令,也可以是一个用于错误处理的语句(就像这里讨论的那样)。

为错误处理取一个不同的名字会很好,而且可能是一个更明显的名字。