24

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

在 C++ 中,如果我想通过值传递,我总是可以依赖复制构造函数来发挥作用。C# 中除了: 1. 显式创建一个新对象 2. 实现 IClonable 然后调用 Clone 方法之外,还有其他方法。

这是一个小例子:

让我们以 C++ 中的类 A 为例,它实现了一个复制构造函数。

一个方法 func1(Class a),我可以通过 func1(objA) 来调用它(自动创建一个副本)

C#中是否存在类似的东西。顺便说一句,我使用的是 Visual Studio 2005。

4

4 回答 4

20

不,C# 中没有等效的复制构造函数。您传递的(按值)是参考

ICloneable也是有风险的,因为它是深还是浅的定义不明确(而且它没有得到很好的支持)。另一种选择是使用序列化,但同样,它可以快速获取比您预期更多的数据。

如果担心您不希望该方法进行更改,则可以考虑使该类不可变。那么没有人可以对它做任何令人讨厌的事情。

于 2008-11-05T08:33:46.783 回答
8

正如已经解释的那样,没有与 C++ 的复制构造函数等效的东西。

另一种技术是使用对象不可变的设计。对于不可变对象,传递引用和副本之间没有(语义)差异。这就是 System.String 的设计方式。其他系统(尤其是函数式语言)更多地应用这种技术。

于 2008-11-05T08:33:14.400 回答
3

根据此链接(已发布):http: //msdn.microsoft.com/en-us/library/s6938f28 (VS.80).aspx

按值传递引用类型如下所示。引用类型 arr 按值传递给 Change 方法。

除非为数组分配了新的内存位置,否则任何更改都会影响原始项目,在这种情况下,更改完全是该方法的本地更改。

class PassingRefByVal 
{
    static void Change(int[] pArray)
    {
        pArray[0] = 888;  // This change affects the original element.
        pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main() 
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);

        Change(arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]);
    }
}

最后,有关更深入的讨论,请参阅 Jon Skeet 在此问题中的帖子:

在 C# 中通过引用或值传递对象

于 2015-11-30T11:31:09.060 回答
0

看看这个

public class Product
{
   public string Name;
   public string Color;
   public string Category;

   public Product(Product o)
   {
      this.Name=o.Name;
      this.Color=o.Color;
      this.Category=o.Category;
   } 
   // Note we need to give a default constructor when override it

   public Product()
   {
   }
} 
public Product Produce(Product sample)
{
   Product p=new Product(sample);
   p.Category="Finished Product";
   return p;
}
Product sample=new Product();
sample.Name="Toy";
sample.Color="Red";
sample.Category="Sample Product";
Product p=Produce(sample);
Console.WriteLine(String.Format("Product: Name={0}, Color={1}, Category={2}", p.Name, p.Color, p.Category));
Console.WriteLine(String.Format("Sample: Name={0}, Color={1}, Category={2}", sample.Name, sample.Color, sample.Category));
于 2011-05-21T07:53:28.990 回答