Istruzione using (Riferimenti per C#)using statement (C# Reference)
Offre una comoda sintassi che verifica l'uso corretto degli oggetti IDisposable.Provides a convenient syntax that ensures the correct use of IDisposable objects. A partire da C# 8,0, l' using
istruzione assicura l'uso corretto degli IAsyncDisposable oggetti.Beginning in C# 8.0, the using
statement ensures the correct use of IAsyncDisposable objects.
EsempioExample
L'esempio seguente mostra come usare l'istruzione using
.The following example shows how to use the using
statement.
string manyLines=@"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";
using (var reader = new StringReader(manyLines))
{
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);
}
A partire da C# 8,0, è possibile usare la sintassi alternativa seguente per l' using
istruzione che non richiede parentesi graffe:Beginning with C# 8.0, you can use the following alternative syntax for the using
statement that doesn't require braces:
string manyLines=@"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";
using var reader = new StringReader(manyLines);
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);
CommentiRemarks
File e Font sono esempi di tipi gestiti che accedono a risorse non gestite (in questo caso handle di file e contesti di dispositivo).File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). Esistono molti altri tipi di risorse non gestite e tipi della libreria di classi che le incapsulano.There are many other kinds of unmanaged resources and class library types that encapsulate them. Tutti questi tipi devono implementare l' IDisposable interfaccia o l' IAsyncDisposable interfaccia.All such types must implement the IDisposable interface, or the IAsyncDisposable interface.
Quando la durata di un oggetto IDisposable
è limitata a un singolo metodo, è necessario dichiararlo e creare un'istanza nell'istruzione using
.When the lifetime of an IDisposable
object is limited to a single method, you should declare and instantiate it in the using
statement. L'istruzione using
chiama il metodo Dispose sull'oggetto in modo corretto e, quando viene usata come illustrato in precedenza, fa in modo che l'oggetto stesso esca dall'ambito non appena viene chiamato il metodo Dispose.The using
statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. All'interno del using
blocco l'oggetto è di sola lettura e non può essere modificato o riassegnato.Within the using
block, the object is read-only and can't be modified or reassigned. Se l'oggetto implementa IAsyncDisposable
anziché IDisposable
, l' using
istruzione chiama DisposeAsync e l'oggetto awaits
restituito ValueTask .If the object implements IAsyncDisposable
instead of IDisposable
, the using
statement calls the DisposeAsync and awaits
the returned ValueTask. Per altre informazioni su IAsyncDisposable , vedere implementare un metodo DisposeAsync.For more information on IAsyncDisposable, see Implement a DisposeAsync method.
L' using
istruzione garantisce che Dispose (o DisposeAsync ) venga chiamato anche se si verifica un'eccezione all'interno del using
blocco.The using
statement ensures that Dispose (or DisposeAsync) is called even if an exception occurs within the using
block. È possibile ottenere lo stesso risultato inserendo l'oggetto all'interno di un try
blocco e chiamando Dispose (o DisposeAsync ) in un finally
blocco; in realtà, questo è il modo in cui l' using
istruzione viene convertita dal compilatore.You can achieve the same result by putting the object inside a try
block and then calling Dispose (or DisposeAsync) in a finally
block; in fact, this is how the using
statement is translated by the compiler. L'esempio di codice precedente si espande al codice seguente in fase di compilazione (si notino le parentesi graffe aggiuntive per creare l'ambito limitato per l'oggetto):The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):
string manyLines=@"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";
{
var reader = new StringReader(manyLines);
try {
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);
} finally
{
reader?.Dispose();
}
}
La sintassi dell'istruzione più recente using
si traduce in codice simile.The newer using
statement syntax translates to similar code. Il try
blocco viene aperto in cui viene dichiarata la variabile.The try
block opens where the variable is declared. Il finally
blocco viene aggiunto alla chiusura del blocco di inclusione, in genere alla fine di un metodo.The finally
block is added at the close of the enclosing block, typically at the end of a method.
Per ulteriori informazioni sull' try
- finally
istruzione, vedere l'articolo try-finally .For more information about the try
-finally
statement, see the try-finally article.
Più istanze di un tipo possono essere dichiarate in una singola using
istruzione, come illustrato nell'esempio seguente.Multiple instances of a type can be declared in a single using
statement, as shown in the following example. Si noti che non è possibile usare variabili tipizzate in modo implicito ( var
) quando si dichiarano più variabili in un'unica istruzione:Notice that you can't use implicitly typed variables (var
) when you declare multiple variables in a single statement:
string numbers=@"One
Two
Three
Four.";
string letters=@"A
B
C
D.";
using (StringReader left = new StringReader(numbers),
right = new StringReader(letters))
{
string? item;
do {
item = left.ReadLine();
Console.Write(item);
Console.Write(" ");
item = right.ReadLine();
Console.WriteLine(item);
} while(item != null);
}
È possibile combinare più dichiarazioni dello stesso tipo usando la nuova sintassi introdotta anche con C# 8, come illustrato nell'esempio seguente:You can combine multiple declarations of the same type using the new syntax introduced with C# 8 as well, as shown in the following example:
string numbers=@"One
Two
Three
Four.";
string letters=@"A
B
C
D.";
using StringReader left = new StringReader(numbers),
right = new StringReader(letters);
string? item;
do {
item = left.ReadLine();
Console.Write(item);
Console.Write(" ");
item = right.ReadLine();
Console.WriteLine(item);
} while(item != null);
È possibile creare un'istanza dell'oggetto risorsa e quindi passare la variabile all' using
istruzione, ma questa non è una procedura consigliata.You can instantiate the resource object and then pass the variable to the using
statement, but this isn't a best practice. In questo caso l'oggetto rimane nell'ambito quando il controllo lascia il blocco using
, anche se probabilmente non avrà più accesso alle relative risorse non gestite.In this case, after control leaves the using
block, the object remains in scope but probably has no access to its unmanaged resources. In altre parole, non è più completamente inizializzato.In other words, it's not fully initialized anymore. Se si tenta di usare l'oggetto di fuori del blocco using
, si rischia di causare la generazione di un'eccezione.If you try to use the object outside the using
block, you risk causing an exception to be thrown. Per questo motivo, è preferibile creare un'istanza dell'oggetto nell' using
istruzione e limitarne l'ambito al using
blocco.For this reason, it's better to instantiate the object in the using
statement and limit its scope to the using
block.
string manyLines=@"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";
var reader = new StringReader(manyLines);
using (reader)
{
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);
}
// reader is in scope here, but has been disposed
Per altre informazioni sull'eliminazione degli oggetti IDisposable
, vedere Uso di oggetti che implementano IDisposable.For more information about disposing of IDisposable
objects, see Using objects that implement IDisposable.
Specifiche del linguaggio C#C# language specification
Per altre informazioni, vedere Istruzione using nella specifica del linguaggio C#.For more information, see The using statement in the C# Language Specification. La specifica del linguaggio costituisce il riferimento ufficiale principale per la sintassi e l'uso di C#.The language specification is the definitive source for C# syntax and usage.
Vedi ancheSee also
- Riferimenti per C#C# Reference
- Guida per programmatori C#C# Programming Guide
- Parole chiave di C#C# Keywords
- Direttiva usingusing Directive
- Garbage CollectionGarbage Collection
- Uso di oggetti che implementano IDisposableUsing objects that implement IDisposable
- Interfaccia IDisposableIDisposable interface
- istruzione using in C# 8,0using statement in C# 8.0