这段代码有什么作用?

Ram*_*esh 4 c#

是什么

using (SqlConnection cn = new SqlConnection(connectionString))
Run Code Online (Sandbox Code Playgroud)

做?

Mar*_*ell 13

new SqlConnection(connectionString)
Run Code Online (Sandbox Code Playgroud)

SqlConnection针对提供的连接字符串创建新实例.

SqlConnection cn = ...
Run Code Online (Sandbox Code Playgroud)

将它分配给保存构造的连接对象的新局部变量cn(作用于using语句).

using(...)
Run Code Online (Sandbox Code Playgroud)

是一个using声明 - 它确保连接Dispose()在结尾处是-d,即使抛出异常(在这种情况下Dispose()意味着关闭它/释放到池等)

整个代码基本上是:

{ // this { } scope is to limit the "cn"
    SqlConnection cn = new SqlConnection(connectionString);
    try { // the body of the using block
        ...
    } finally { // dispose if not null
        if(cn != null) { cn.Dispose(); }
    }
}
Run Code Online (Sandbox Code Playgroud)