c# 參數 params ,ref ,out

1.params :傳遞多個參數,在通常在不確定參數個數的情況下使用,而且可以不限定參數類型。

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace variable
{
    class Program
    {
        static void Main(string[] args)
        {
            print("information", new Field("Name", "mengyu"), new Field("aa", "bb"));
        }
        static void print(string a, params object[] args)
        {
            Console.WriteLine(a);
            foreach (object obj in args)
            {
                Field field = (Field)obj;
                Console.WriteLine(field.Name + "=" + field.Value);
            }
            Console.Read();
        }
    }
    class Field
    {
        private string name;
        private string value;
        public Field(string name, string value)
        {
            this.name = name;
            this.value = value;

        }
        public string Name
        {
            get { return name; }
            set { name = value; }

        }
        public string Value
        {
            get { return value; }
            set { this.value = value; }
        }
    }
    
}
</span>
2.ref:使參數按照引用類型傳遞,通過這句話我們可以想到的是,引用類型傳遞的不是地址麼,那麼我們是否可以這樣理解,這種形式的參數的傳遞實際也是傳遞的地址,那麼當你傳參的時候,變量的值也跟着參數改變了。

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace variable
{
    class Program
    {
        public static void UseRef(ref int i)
        {
            i += 100;
            Console.WriteLine("i={0}", i);
        }
        static void Main()
        {
            int i = 10;
            Console.WriteLine("Before the method calling :i={0}", i);
            UseRef(ref i);
            Console.WriteLine("After the method calling :i={0}", i);
            Console.Read();
        }
    }
}</span>
圖中結果可以看出:變量i的值本來是10,經過參數傳遞後變量的值變成110.

3.out  跟ref相同也是按引用傳遞,但是ref參數變量需要先賦值,而out參數不需要。

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace variable
{
    class Program
    {
        static void Method(out int i)
        {
            i = 44;
            Console.WriteLine(i);
        }
        static void Main()
        {
            int value;
            Method(out value);
            Console.WriteLine(value );
            Console.Read();
        }
    }
}
</span>


需要測試的小夥伴可以把上面代碼中的out去掉後看看會發現什麼。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章