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>