Isn't the using and as operators in c # used by many people? Don't even know?
In fact, these two operators are very useful in small places.
1. using
According to the msdn explanation
The using statement defines a range where objects are processed at the end of the range.
Example:
Class TestUsing: IDisposable
{
Public void Dispose ()
{
Console. WriteLine ("Dispose ");
}
Public void Method ()
{
Console. WriteLine ("Do a method ");
}
}
Call this class:
Using (TestUsing tu = new TestUsing ())
{
Tu. Method ();
}
We can see that Do a method and Dispose are output successively.
Note: The instantiated object must implement the System. IDisposable interface.
2.
Msdn says:
The as operator is used to convert compatible types.
The as operator is similar to the type conversion. The difference is that when the conversion fails, the as operator will generate null instead of exception. In form, this form of expression:
Expression as type
It is equivalent:
Expression is type? (Type) expression: (type) null
Expression is calculated only once.
Note that the as operator only performs reference conversion and packing conversion. The as operator cannot execute other conversions, such as user-defined conversions. cast expressions should be used for such conversions.
Example:
Object [] arr = new object [2];
Arr [0] = 123;
Arr [1] = "test ";
Foreach (object o in arr)
{
String s = (string) o;
Console. WriteLine (s );
}
This code causes an exception when the conversion type fails. The code is changed:
Object [] arr = new object [2];
Arr [0] = 123;
Arr [1] = "test ";
For (int I = 0; I <arr. Length; I ++)
{
String s = arr [I] as string;
If (s! = Null) Console. WriteLine (I + ":" + s );
} We can see that 1: test is output. Although the conversion fails at arr [0], but no exception is thrown, null is returned.
Note: as must be used with the reference type (int equivalent type cannot be used)