講解一下ref與out的小知識,形象總結的例子讓您運用起來的心應手,新手一看就懂,共同進步。ide
- class Program
- {
- static void Main(string[] args)
- {
- //兩次調用show1方法,比較兩次的a值
- int a = 0;
- show1(a);
- Console.WriteLine(a);
- show1(a);
- Console.WriteLine(a + "\n");
- //兩次調用show1的ref重載方法,比較兩次的a值
- int b = 0;
- show1(b);
- Console.WriteLine(b);
- show1(b);
- Console.WriteLine(b + "\n");
- //調用show2方法(注:show1方法已經定義了ref的重載方法,則不能定義out的重載方法)
- int c = 0;
- show2(out c);
- Console.WriteLine(c);
- //調用show3方法返回兩個不一樣類型的值
- int d = 0;
- string e = show3(out d);
- Console.WriteLine(d);
- Console.WriteLine(e);
- }
- ///方法一
- protected static void show1(int i1)
- {
- i1++;
- }
- ///方法二
- protected static void show1(ref int i1)
- {
- i1++;
- }
- ///方法三
- protected static void show2(out int i1)
- {
- i1 = 5;
- }
- ///方法四
- protected static string show3(out int i1)
- {
- i1 = 5;
- return "注意我是怎麼返回了兩個不一樣類型值呢";
- }
注:1.使用控制檯演示一下很是直觀,易懂spa
2.放法1,2和1,3比較您會分別瞭解ref,out方法的用途與原理。xml
3.方法2,3比較您會深入體會ref與out兩種引用傳遞的根本區別,ref的地址引用傳遞和out的值傳遞,ref會爲變量開闢一塊內存空間,保存該變量的地址,直到程序關閉。內存
4.方法3,4比較您會了解out最經常使用的用法,方便實用。string