Passing Reference types by value in C#
I want to pass a reference type by value to a method in C#. Is there a way to do it.
In C++, I could always rely on the copy constructor to come into play if I wanted to pass by Value. Is there any way in C# except: 1. Explicitly creating a new object 2. Implementing IClonable and then calling Clone method.
Here's a small example:
Let's take a class A in C++ which implements a copy constructor.
A method func1(Class a), I can call it by saying func1(objA) (Automatically creates a copy)
Does anything similar exist in C#. By the way, I'm using Visual Studio 2005.
No, there is no copy-constructor equivalent in C#. What you are passing (by value) is a reference.
ICloneable
is also risky, since it is poorly defined whether that is deep vs shallow (plus it isn't very well supported). Another option is to use serialization, but again, that can quickly draw in much more data than you intended.
If the concern is that you don't want the method making changes, you could consider making the class immutable. Then nobody can do anything nasty to it.
As already explained, there's no equivalent to C++'s copy constructors.
Another technique is to use a design where the objects are immutable. For immutable objects there is no (semantic) difference between passing a reference and a copy. This is the way System.String is designed. Other systems (notably functional languages) apply this technique much more.
这个链接shd回答你的问题 - http://msdn.microsoft.com/en-us/library/s6938f28(VS.80).aspx
链接地址: http://www.djcxy.com/p/21020.html上一篇: String和C#中的字符串有什么区别?
下一篇: 在C#中通过值传递引用类型