關于這三個關鍵字之前可以研究一下原本的一些操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using system; using system.collections.generic; using system.text; namespace paramsrefout { class program { static void changevalue( int i) { i=5; console.writeline( "the changevalue method changed the value " +i.tostring()); } static void main( string [] args) { int i = 10; console.writeline( "the value of i is " +i.tostring()); changevalue(i); console.writeline( "the value of i is " + i.tostring()); console.readline(); } } } |
觀察運行結果發現
值并沒有被改變,也就是說此時的操作的原理可能也是跟以前c語言的函數操作是一樣的
本文主要討論params關鍵字,ref關鍵字,out關鍵字。
1)params關鍵字,官方給出的解釋為用于方法參數長度不定的情況。有時候不能確定一個方法的方法參數到底有多少個,可以使用params關鍵字來解決問題。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using system; using system.collections.generic; using system.text; namespace paramsrefout { class number { public static void useparams( params int [] list) { for ( int i=0;i<list.length;i++) { console.writeline(list[i]); } } static void main( string [] args) { useparams(1,2,3); int [] myarray = new int [3] {10,11,12}; useparams(myarray); console.readline(); } } } |
2)ref關鍵字:使用引用類型參數,在方法中對參數所做的任何更改都將反應在該變量中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using system; using system.collections.generic; using system.text; namespace paramsrefout { class number { static void main() { int val = 0; method( ref val); console.writeline(val.tostring()); } static void method( ref int i) { i = 44; } } } |
3) out 關鍵字:out 與ref相似但是out 無需進行初始化。
以上所述是小編給大家介紹的c#中三個關鍵字params,ref,out,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!