BigInteger 如何传入函数

How are BigInteger passed in functions

C# 中的 BigIntegers 是按值传递还是按引用传递?我有一个代码,我需要在其中按值传递它们,我认为它们是作为参考传递的,因为在初始调用函数中进行了一些调用后值发生了更改,但不确定是否确实如此。

请帮忙:)

BigInteger is a struct, so it is a value type and it is passed by value 默认:

Because a struct is a value type, when you pass a struct by value to a method, the method receives and operates on a copy of the struct argument. The method has no access to the original struct in the calling method and therefore can't change it in any way. The method can change only the copy.

Passing Value-Type Parameters (C# Programming Guide)

A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no effect on the original data stored in the argument variable. If you want the called method to change the value of the argument, you must pass it by reference, using the ref or out keyword. You may also use the in keyword to pass a value parameter by reference to avoid the copy while guaranteeing that the value will not be changed. For simplicity, the following examples use ref.

如果你想通过引用传递这样的类型,你可以使用ref关键字。

Passing Reference-Type Parameters (C# Programming Guide)

A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data belonging to the referenced object, such as the value of a class member. However, you cannot change the value of the reference itself; for example, you cannot use the same reference to allocate memory for a new object and have it persist outside the method. To do that, pass the parameter using the ref or out keyword. For simplicity, the following examples use ref.

因此,只有内存指针(在 x32 或 x64 系统上为 4 或 8 个字节)在调用方法(如 class 的实例)之前被压入堆栈,而不是整个结构内容(所有成员的副本,例如,如果结构至少有 8 个整数,则为 8x4 字节)。

Pass c# struct by reference

Passing a struct by Reference

Pass reference by reference vs pass reference by value - C#

Passing a Reference vs. Value (Pluralsight)

Understanding C# Pass by Reference and Pass by Value (Udemy)

Passing Arguments By Value and By Reference (C# 6 for Programmers, 6th Edition)

从技术上讲,C# 中的所有 对象(以及Java)都是按值传递的(默认) .

  • 对于引用类型,这个值恰好是一个reference(指针)。这就是方法内部的更改会影响实际对象的原因。
  • 对于值类型,这个值是变量持有的实际值。这就是方法内部的更改不会影响实际对象的原因。

BigInteger 无论如何都不是特别的,它是一个 struct (这是一个值类型)。

如果要通过引用传递对象,可以使用 ref 关键字。

另请参阅:

您可能还想查看 this question 的答案。