1. 程式人生 > >不要忽略c#中的using和as操作符

不要忽略c#中的using和as操作符

是不是很多人不用c#中的using和as操作符?甚至不知道?
其實這2個操作符在小處非常有用。

1、using
按照msdn的解釋  

using 語句定義一個範圍,在此範圍的末尾將處理物件。

舉例:

class TestUsing:IDisposable
    
{
        
publicvoid Dispose() 
        
{
            Console.WriteLine(
"Dispose"); 
        }


        
publicvoid Method()
        
{
            Console.WriteLine(
"Do a method");
        }

    }

呼叫這個類:

using(TestUsing tu=new TestUsing())
            
{
                tu.Method();
            }

可以看到先後輸出了Do a method和Dispose。
備註:例項化的物件必須實現 System.IDisposable 介面

2、as
msdn這麼說:

as 運算子用於執行可相容型別之間的轉換。
as 運算子類似於型別轉換,所不同的是,當轉換失敗時,as 運算子將產生空,而不是引發異常。在形式上,這種形式的表示式:

expression 
as type
等效於:

expression 
is type ? (type)expression : (type)null
只是 expression 只被計算一次。

請注意,
as 運算子只執行引用轉換和裝箱轉換。as 運算子無法執行其他轉換,如使用者定義的轉換,這類轉換應使用 cast 表示式來代替其執行。


舉例:
object [] arr=newobject[2];
            arr[
0]=123;
            arr[
1]="test";
            
foreach(object o in arr)
            
{
                
string s=(string)o;
                Console.WriteLine(s);
            }

這樣的程式碼在轉換型別失敗的時候引發異常,程式碼修改成:
object [] arr=newobject[2];
            arr[
0]=123;
            arr[
1]="test";
            
for(int i=0;i<arr.Length;i++)
            
{
                
string s=arr[i] asstring;
                
if(s!=null)Console.WriteLine(i+":"+s);
            }
可以看到輸出了1:test,雖然arr[0]處轉換失敗但是沒有引發異常而是返回了null

備註:as必須和引用型別一起使用(int等值型別不能使用)