值类型参数按值传递 class Program { static void Main(string[] args) {
class Program
{
static void Main(string[] args)
{
int a = 10;
Add(a);
Console.WriteLine("传递之后的值为:" + a);
Console.ReadKey();
}
private static void Add(int i)
{
Console.WriteLine("传递之前的值为:" + i);
i = i + 10;
}
}
结果:
可见,值类型参数在被方法调用的时候,是对本身实例的拷贝和操作,在方法调用前后参数值不变。
当引用类型参数传递时,是对托管堆上对象实例内容的操作。
也就是引用类型按值传递,传递的是引用变量的指针,指向托管堆上的对象实例。
class Program
{
static void Main(string[] args)
{
Student student = new Student();
Add(student);
Console.WriteLine("参数传递之后的值为:" +student._score);
Console.ReadKey();
}
private static void Add(Student s)
{
Console.WriteLine("参数传递之前的值为:" + s._score);
s._score = 90;
}
}
public class Student
{
public int _score = 80;
}
结果
可见,引用类型参数在被方法调用的时候,是针对变量的引用的操作,一旦引用对象内容发生改变,原来变量的值也随着改变。
引用类型参数按值传递和按引用传递的不同之处:
另外,值类型也有按引用传递,这时候,传递的是值类型的地址。
class Program
{
static void Main(string[] args)
{
int i = 100;
string str = "one";
ChangeByValue(ref i);
ChangeByRef(ref str);
Console.WriteLine(i);
Console.WriteLine(str);
Console.ReadKey();
}
private static void ChangeByValue(ref int iValue)
{
iValue = 200;
}
private static void ChangeByRef(ref string sValue)
{
sValue = "One more";
}
}
可见,不管是值类型,还是引用类型,加入关键字ref作为参数,就意味着是对参数地址的操作,即托管堆上实例地址的改变。
另外:
out告诉编译器,参数会在方法内部初始化,而在方法之前不需要初始化。
int x;
Foo(out x);
ref告诉编译器,参数在方法之前必须初始化。
int y = 0;
Foo(ref y);
class Program
{
static void Main(string[] args)
{
string str = "Old String";
Console.WriteLine("传递之前的值为:" + str);
ChangeStr(str);
Console.WriteLine("传递之后的值为:"+str);
Console.ReadKey();
}
private static void ChangeStr(string astr)
{
astr = "Change String";
}
}
结果:
可见,虽然string是引用类型,但按值传递的表现和值类型按值传递的表现一样。
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程网的支持。如果你想了解更多相关内容请查看下面相关链接
--结束END--
本文标题: C#中参数的传递方式详解
本文链接: https://www.lsjlt.com/news/171287.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0