对值类型和引用类型的理解
对C#中用new关键字实例化对象的理解
在调用方法时,将变量存储的数据复制给方法。具体而言,方法的参数(即形参)在内存中有自己的存储数据的空间,复制的数据被存储在其空间中。
【例子】
class Program
{
static void Main(string[] args)
{
Program ps=new Program();
int y = 10;//值类型
string str = "asd";//引用类型
Test test=new Test();//引用类型
test.a = 10;
ps.ValueParameter(y,str,test);
Console.WriteLine(y+" "+str+" "+test.a);
Console.ReadKey();
}
public void ValueParameter(int x,string str,Test test)
{
x += 10;
str += "fgh";
test.a += 10;
Console.WriteLine(x+" "+str+" "+test.a);
}
}
class Test
{
public int a;
}
【输出】
【总结】
在调用方法时,将变量的引用传递给方法。可以认为直接将变量传给方法,而不是像值参数一样把副本传给方法。
【例子】
ps.ReferenceParameter(ref y,ref str,ref test);
public void ReferenceParameter(ref int x,ref string str,ref Test test)
{
x += 10;
str += "fgh";
test.a += 10;
Console.WriteLine(x + " " + str + " " + test.a);
}
【输出】
【总结】
同ref类似,传递引用。使用ref时,方法会读取参数的值并重新赋值;使用out时,方法不会读取参数的值,只向参数赋值,参数会被认为是初始化的,即使参数有值。
【例子】
ps.OutParameter(out y, out str, out test);
public void OutParameter(out int x, out string str, out Test test)
{
x = 20;//x = x+10会报错,因为x被认为是未初始化的,即未赋值
str = "fgh";
Test test2=new Test();
test2.a = 20;
test = test2;
Console.WriteLine(x + " " + str + " " + test.a);
}
【输出】
【总结】
允许在调用方法时提供类型相同、数量可变的参数。
【例子】
ps.ParameterArray(2,3,"sss","aaa");
ps.ParameterArray(34,56,"aaa","987","kkk");
public void ParameterArray(int x, int y, params string[] str)
{
string str2 = "";
foreach (string s in str)
{
str2 += s;
}
Console.WriteLine(x + " " + y + " " + str2);
}
【输出】
【总结】
为参数提供默认值,在调用方法时可以不用给某些参数提供实参,即允许在调用方法时提供类型不同、数量可变的参数。
【例子】
ps.OptionParameter(2);
ps.OptionParameter(2,10);
ps.OptionParameter(2, 10,"sss");
public void OptionParameter(int x, int y = 5, string str = "enternalstar")
{
Console.WriteLine(x + " " + y + " " + str);
}
【输出】
【总结】
【命名参数】
之前调用方法时必须按照方法中参数的顺序给参数赋值,使用命名参数可以不按照这个顺序。
【例子】
ps.NamedParameter(10,name:"sxd",y:10);
public void NamedParameter(int x,int y=5,string str = "enternalstar",string name="aaa")
{
Console.WriteLine(x + " " + y + " " + str+" "+name);
}
【输出】
【总结】
方法有输入和输出,一般来说,输入的数量要多于输出。在各种不同的应用中,我们可能对输入和输出有不同的要求,例如有时我们希望输入的变量在调用方法后不会改变,有时希望能改变;有时我们可以确定要输入的参数数量,有时我们又不能确定要输入的参数数量;有时只要有一个输出就可以,有时要多个输出。
C#中提供的几种参数类型可以满足我们在各种不同应用中对输入和输出的要求。
如果我们希望变量的值在调用方法后不会改变,用值类型;
如果我们希望变量的值在调用方法后可以改变,一般用ref参数;
如果我们希望有多个返回值,可以用out参数;
如果我们有些参数会根据具体的情况来看用不用得到,那么可以用params参数;
如果有些参数在很多情况下用一个值就可以了,重复输入让我们感觉麻烦,那么用可选参数,给参数提供默认值;
如果方法有很多参数,有些参数有默认值,我们想跳过中间的参数,直接给那些靠后的参数赋值,那么用命名参数。