經常看見ref、out、param這三個參數修飾符,在C#中偶爾使用一下,這三個參數修飾符是從C裡面發展過來的,
簡單說明下:
ref 和 out 主要是傳遞參數時使用的,比如你寫了一個方法傳回string類型,
- private string MyFunction()
- {
- return"abc";
- }
你也可以換成下面的形式:
- private void MyFunction(ref string str)
- {
- str="abc";
- }
或者這樣:
- private void MyFunction(out string str)
- {
- str="abc";
- }
那怎麼調用這個函數呢。。
- // 針對于ref參數修飾符
- string returnValue=string.Empty;
- MyFunction(ref returnValue);
- // 針對于out參數修飾符
- string returnValue;
- MyFunction(out returnValue);
從兩者的調用上就可以看出差別,在帶有ref參數修飾符的參數時,必須給ref參數初始化值,
string returnValue=string.Empty;
代碼中給參數初始化為空。
這是因為帶有ref參數修飾符的參數是傳遞的位址,
而out參數修飾符是傳回的值。