Using statement

xiaoxiao2021-03-06  42

Create an instance in the USING statement to ensure that DISPOSE is called on the object when exiting the USING statement. When you reach the end of the USING statement, or if an exception is triggered before the end of the statement, you can exit the USING statement. The instantiated object must implement the System.IDisposable interface. Example // cs_using_statement.cs // compile with /reference :system.drawing.dllusing system.drawing; class a {public static void main () {use (font myfont = new font ("arial", 10.0f), myfont2 = New font ("arial", 10.0f)) {// use myfont and myfont2} // compiler Will Call Dispose On Myfont and MyFont2

Font myfont3 = new font ("arial", 10.0f); using (myfont3) {// use myfont3} // Compiler Will Call Dispose On MyFont3

}

Do not realize the System.idisposable interface is unable to use using. The font class in this example is a system class that comes with VS.NET, which has implemented the interface. public sealed class Font: MarshalByRefObject, ICloneable, ISerializable, IDisposable if it is to write, generally written as follows: public class AAA: System.IDisposable {public AAA () {//} public void CC () {//} public void Dispose ( ) {//}} For C # programmers, make sure that a simple way to close the Connection and DataReader objects often use the USING statement.

The USING statement automatically invokes Dispose on the used objects within the USING statement, as shown below:

// c # string connString = "Data Source = localhost; integrated security = sspi; initial catalog = northwind;"

Using (SqlConnection conn = new sqlconnection) {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)); }

转载请注明原文地址:https://www.9cbs.com/read-55811.html

New Post(0)