简体   繁体   中英

C#: Purpose of `using` statement with braces and anonymous object

I know that in C# using with braces is used to ensure that the object is disposed like the following:

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

Thus, this code is completely clear.
But I am reading a code where using with braces is used with anonymous instantiation. Here some samples:

public partial class FrmAuthenticate : Form
{
    public String Username { get; set; }
    public String Password { get; set; }
    private void btnOk_Click(object sender, EventArgs e)
    {
        NetworkCredential writeCredentials = new NetworkCredential(txtUsername.Text, txtPassword.Text);
        using (new NetworkConnection(IpPath, writeCredentials))
        {
            Username = txtUsername.Text;
            Password = txtPassword.Text;
        }
    }
}

or

using (new NetworkConnection(TargetProgramSldDir, writeCredentials))
using (new NetworkConnection(@"\\"+ this.TargetServerIp, writeCredentials))
{
    if (Directory.Exists(TargetProgramSldDir + @"\MyService"))
        Copy(TargetProgramSldDir + @"\MyService", backupDir + @"\MyService");
}

How are the anonymous objects used in the two cases? How is the created object of NetworkConnection used in the two codes? I don't understand what the purpose of the using statement of especially the first sample code is?

How is the created object of NetworkConnection used in the two codes?

It's just disposed at the end of the block.

I assume that what's happening is that the constructor will fail if the credentials are invalid - so in that case, the properties are never updated. If the constructor succeeds, the properties are updated and then the NetworkConnection is disposed.

One problem with the code as it stands is that the exception isn't caught - it will propagate up into the event loop, which hopefully has an exception handler attached - but it's really not terribly pleasant.

If this were code in a code-base I was maintaining, I'd try to refactor it to something like:

if (NetworkConnection.TestCredentials(IpPath, writeCredentials))
{
    Username = txtUsername.Text;
    Password = txtPassword.Text;
}
else
{
    // Report the error to the user
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM