不僅可以通過值爲方法傳遞參數,還可以通過引用爲方法傳遞參數,若通過引用爲方法傳遞參數,需要使用ref關鍵字
如果把一個參數傳遞給方法,且這個方法的輸入參數前帶有ref關鍵字,那麼這個方法對參數所作的任何改變都會影響原來對象的值
注意
1:通過ref傳遞的引用參數,在函數成員調用之前,必須已賦值,如果沒有明確賦值會報錯
實例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _5_ref
{
class Program
{
static void Main(string[] args)
{
string sex = "男";
Person person = new Person();
string name = person.GetName(ref sex);
Console.WriteLine("{0}{1}",name,sex);
Console.ReadKey();
}
}
class Person
{
public string GetName(ref string strSex)
{
if (strSex == "男")
{
strSex = "女";
return "韓梅梅";
}
else
{
strSex = "男";
return "李磊";
}
}
}
}
運行效果
我們可以看到我們的sex的值本身發生了變化,變成了“女”