按值在C#中传递引用类型 [英] Passing Reference types by value in C#

查看:99
本文介绍了按值在C#中传递引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过值引用类型传递给在C#中的方法。有没有办法做到这一点。

I want to pass a reference type by value to a method in C#. Is there a way to do it.

在C ++中,我总是可以依靠拷贝构造函数来发挥作用的,如果我想按值传递。有没有在C#中,除了任何方式:
1.明确创建新对象
2.实施IClonable,然后调用Clone方法

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.

下面是一个小例子:

让我们以C ++中的A类它实现了一个拷贝构造函数

Let's take a class A in C++ which implements a copy constructor.

一个方法FUNC1( A级),我可以说的func1(objA称呼它)(自动创建副本)

A method func1(Class a), I can call it by saying func1(objA) (Automatically creates a copy)

做任何事情存在类似C#中。顺便说一句,我使用的Visual Studio 2005。

Does anything similar exist in C#. By the way, I'm using Visual Studio 2005.

推荐答案

没有,没有拷贝构造相当于在C#。你所传递(按价值计算)是的参考

No, there is no copy-constructor equivalent in C#. What you are passing (by value) is a reference.

ICloneable 也有风险的,因为它是定义不清是否是深深浅浅的VS(再加上它没有很好的支持)。另一种选择是使用序列化,但同样,它可以快速绘制更多的数据比你预期的。

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.

这篇关于按值在C#中传递引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆