按值或在C#中通过引用 [英] by value or by reference in c#
本文介绍了按值或在C#中通过引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我在c#中创建了一个类:
Hello,
I created a class in c#:
public myClass()
{
.....
}
1)如果我像这样分配课程:
1) If I assign the class like this:
myClass m1 = new myClass();
....
myClass m2 = m1;
是将m1(按值)复制到m2,还是通过引用进行分配?
2)我创建了一个ArrayList.
如果我将myClass的实例添加到ArrayList中,将按值(副本)还是按引用添加它?
谢谢
will m1 be copied (by value) to m2, or will it be assigned by reference?
2)I created an ArrayList.
If I add an instance of myClass to the ArrayList, will it be added by value (copy) or by reference?
Thanks
推荐答案
如果是类,它将由ref分配:)
If it is class, it will be assigned by ref :)
类始终是引用(结构是Value)类型和引用始终是引用的副本,而不是类本身内的值,除非创建了副本构造函数并明确使用: ^ ]
因此,将引用值分配给另一个引用变量将始终导致两个引用指向"同一数据实例:
Classes are always References (structs are Value types) and References are always copies of the reference, not the values within the class itself unless a copy constructor is created, and used explicitly: http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx[^]
So an assignment of a reference value to another reference variable will always result in two references that "point" at the same data instance:
MyClass m1 = new MyClass();
m1.Name = "Joe";
MyClass m2 = m1;
Console.WriteLine (m1.Name + " = " + m2.Name);
m1.Name = "Mike";
Console.WriteLine (m1.Name + " = " + m2.Name);
将输出:
Will output:
Joe = Joe
Mike = Mike
这篇关于按值或在C#中通过引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文